Java(处理环境)不会向我提供本地时间
我正在尝试根据本地时区调整 epoc 时间(即 GMT-7,但它显示 GMT)。我相当确定这应该有效,但事实并非如此......
Calendar localTime = new GregorianCalendar(TimeZone.getDefault());
Date dd = localTime.getTime();
long t = dd.getTime()/1000;
System.out.printf("%d\n",t);
但它仍然根据 GMT 输出 epoc 时间,而不是 GMT-7 (我的时区)。玩了一段时间后,我确实让它工作了......
Date ddd = new Date();
long t = ddd.getTime() + TimeZone.getDefault().getOffset( ddd.getTime() );
t = t/1000;
但为什么第一个块不工作?
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 dd = 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Date
对象只是将 UTC 时间(自纪元以来的毫秒数)封装起来。这就是 Java 中所有时间在“幕后”的表示方式。这也使其工作起来保持一致。每当您想要打印某些内容时,请对其应用时区偏移量和 DST 偏移量。这就是
SimpleDateFormat
类接受 TimeZone 但Date
类上没有 TimeZone 设置器的原因。强制:我听说 Joda Time 是一个更容易使用的日期时间 API。
另外,请查看这篇文章,了解 Java 中的标准日期和时间库。
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 theDate
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.