新日期(长)给出不同的结果 [英] new Date(long) gives different results
问题描述
当我运行这段代码:
System.out.println( "XXX date=" + new Date( 1311781583373L ) );
我在Eclipse的JUnit转轮中得到这个结果:
I get this result in Eclipse's JUnit runner:
XXX date=Wed Jul 27 16:46:23 GMT+01:00 2011
,并从命令行导致Maven:
and this result in Maven from the command line:
XXX date=Wed Jul 27 17:46:23 CEST 2011
如你所见,小时不一样。
As you can see, the hour is different.
(相同的计算机,相同的Java版本,也许30秒)。为什么?
(same computer, same Java version, maybe 30s apart). Why?
时区也不同。当从Eclipse开始时,为什么Java从Maven开始使用 CEST
?从Eclipse开始时, GMT + 01:00
Also the time zone is different. Why is Java using CEST
when it's started from Maven and GMT+01:00
when started from Eclipse?
或者换句话说:如何强制Java使用?
Or to put it another way: How can I force Java to use either?
推荐答案
要指定默认时区,您可以设置系统属性 user.timezone
。您可以通过将其作为参数传递给JavaVM来执行此操作(您可能需要修改eclipse.ini或Maven等效配置文件):
To specify the default timezone you can set the system property user.timezone
. You can do this by passing it as an argument to the JavaVM (you may need to modify eclipse.ini or Maven equivalent config file):
-Duser.timezone=<your preferred timezone>
...或通过编程方式设置:
...or by setting it programmatically:
System.setProperty("user.timezone", "<your preferred timezone>");
或者,如果方便,您可以指定每次打印日期时使用的时区:
Or, if it is convenient you can specify a timezone which you use each time you print out the date:
DateFormat myDateFormat = new SimpleDateFormat("<insert date format string here>");
myDateFormat.setTimeZone(TimeZone.getTimeZone("<your preferred timezone>"));
....
System.out.println(myDateFormat.format(yourDate));
这篇关于新日期(长)给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!