java 时区、日历和 SimpleDateFormat 的奇怪问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2092340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:23:44  来源:igfitidea点击:

Strange problem with timezone, calendar and SimpleDateFormat

javadatecalendarsimpledateformat

提问by Romain Linsolas

Let's consider the following code:

让我们考虑以下代码:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US);
long start = sdf.parse("10:30:00 30/09/2009").getTime();
long end = sdf.parse("10:30:00 30/10/2009").getTime();

Calendar c = Calendar.getInstance(Locale.US);
c.setTimeInMillis(start);
System.out.println("Start = " + c.getTime());
c.setTimeInMillis(end);
System.out.println("  End = " + c.getTime());

When running this code snippet, I have the following output:

运行此代码片段时,我有以下输出:

Start = Wed Sep 30 10:30:00 CEST 2009
  End = Fri Oct 30 10:30:00 CET 2009

Why do I get different timezone ?

为什么我得到不同的时区?

Note that if I set the first date in august and the second one in september, the output will display the same timezone in both cases:

请注意,如果我将第一个日期设置为 8 月,将第二个日期设置为 9 月,则输出将在两种情况下显示相同的时区:

long start = sdf.parse("10:30:00 30/08/2009").getTime();
long end = sdf.parse("10:30:00 30/09/2009").getTime();

will display:

将显示:

Start = Sun Aug 30 10:30:00 CEST 2009
  End = Wed Sep 30 10:30:00 CEST 2009

I'm using Java 1.6.0_14

我正在使用 Java 1.6.0_14

回答by kgiannakakis

CESTis Central European Summer Time. It is the same as CETwith daylight savings into effect.

CEST是中欧夏令时。这CET与夏令时生效相同。

回答by user85421

You can set the default time zone

您可以设置默认时区

    import java.util.TimeZone;
...        
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));  // or "Etc/GMT-1"

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US);
    long start = sdf.parse("10:30:00 30/09/2009").getTime();
    long end = sdf.parse("10:30:00 30/10/2009").getTime();

    Calendar c = Calendar.getInstance(Locale.US);
    c.setTimeInMillis(start);
    System.out.println("Start = " + c.getTime());
    c.setTimeInMillis(end);
    System.out.println("  End = " + c.getTime());

use TimeZone.getAvailableIDs()to see all available IDs.

用于TimeZone.getAvailableIDs()查看所有可用的 ID。

EDIT: you can also use a new SimpleTimeZone

编辑:您还可以使用新的 SimpleTimeZone

    TimeZone.setDefault(new SimpleTimeZone(60 * 60 * 1000, "CET"));

回答by nanda

Yes, it is related to the daylight saving time. If you use a time zone that recognizes DST, it will be automatically used. You can use GMT for example if you don't want this.

是的,这与夏令时有关。如果您使用可识别 DST 的时区,它将自动使用。例如,如果您不想要这个,您可以使用 GMT。