开发者

Java (Processing Environment) will not provide me with the local time

I'm trying to get the epoc time adjusted for the local timezone (i.e. GMT-7, but it displays GMT). I'm fairly sure this should work, but it's not...

Calendar localTime = new GregorianCalendar(TimeZone.getDefault());
Date d开发者_开发问答d = localTime.getTime();
long t = dd.getTime()/1000; 
System.out.printf("%d\n",t);

But it still outputs the epoc time based on GMT, not GMT-7 (my timezone). After playing around for some time I did get this to work...

Date ddd = new Date();
long t = ddd.getTime() + TimeZone.getDefault().getOffset( ddd.getTime() );
t = t/1000;

But why isn't the first block working?


A Date object simply wraps the UTC time in milliseconds since the epoch. This is how all time is represented 'under the hood' in Java. This also makes it consistent to work with. Whenever you want to print something out, apply the TimeZone offset and DST offset to it.

This is why the SimpleDateFormat class accepts a TimeZone but there is no TimeZone setter on the Date class.

Obligatory: I have heard Joda Time is a much easier to use datetime API.

Also, have a look at this post on the standard date and time libraries in Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜