繁体   English   中英

Java:将MST转换为EST

[英]Java: Convert MST to EST

我一直在尝试转换从时代到今天的时间,并将其显示在东部标准时间。 这是远程计算机(远程托管)上的输出:

Date now = new Date(System.currentTimeMillis());
System.out.println(now.toString());
// Thu Apr 24 14:36:11 MST 2014

不知道什么是MST ,但我想获取自EST时代以来的当前毫秒数,并在EST中显示结果。

无论我做什么,我都无法节省夏令时的工作(目前是EST时区中的夏令时); 我要么以PST,GMT或UTC结束,当我得到“ EST”时,它要么是某个随机值,要么是落后1小时或落后3小时。

我希望使用此DateFormat格式化输出:

DateFormat EXPIRE_FORMAT = new SimpleDateFormat("MMM dd, yyyy h:mm a z");

只需使用DateFormat#setTimeZone(TimeZone)设置要显示时间的时区

Date now = new Date(System.currentTimeMillis());
DateFormat EXPIRE_FORMAT = new SimpleDateFormat("MMM dd, yyyy h:mm a z");
EXPIRE_FORMAT.setTimeZone(TimeZone.getTimeZone("America/Montreal")); // or whatever relevant TimeZone id 
System.out.println(EXPIRE_FORMAT.format(now));

AFAIK, 目前没有EST。 春季全都是EDT。

以上印刷品

Apr 24, 2014 5:53 PM EDT

Sotirios Delimanolis的评论和回答是正确的。

避免使用3或4个字母时区代码

您应该避免时区使用3或4个字母代码,因为它们既不是标准化的也不是唯一的。 而是使用正确的时区名称 ,通常是大洲+城市

避免juDate

众所周知,与Java捆绑在一起的java.util.Date和.Calendar&SimpleDateFormat类非常麻烦。 将体面的日期时间库与更新的时区数据库一起使用。 对于Java,这意味着Joda-Time或Java 8中新的java.time包(受Joda-Time启发)。

避免自毫秒以来的毫秒

我建议您避免从epoch开始使用毫秒。 由于数字在被人阅读时毫无意义,因此会很快造成混乱。 让日期时间库为您管理毫秒。

指定时区

通常最好指定所需/预期的时区。 如果省略时区,则所有主要的日期时间库(java.util.Date,Joda-Time,java.time)都将应用JVM的默认时区。

Joda-Time示例

Joda-Time 2.3中的示例代码。

DateTimeZone timeZoneToronto = DateTimeZone.forID( "America/Toronto" );
DateTime dateTimeToronto = new DateTime( timeZoneToronto ); // Current moment.
DateTime dateTimeUTC = dateTimeToronto.withZone( DateTimeZone.UTC );
DateTime dateTimeParis = dateTimeToronto.withZone( DateTimeZone.forID( "Europe/Paris" ) );

如果您确实想要自纪元以来的毫秒数,请调用getMillis方法。 在上面的示例代码中,所有三个DateTime对象具有相同的毫秒数(自纪元以来)。

long millis = dateTimeToronto.getMillis();

如果您需要将java.util.Date与其他类一起使用…

java.util.Date date = dateTimeToronto.toDate();

尽管Joda-Time使用ISO 8601标准格式作为默认格式,但您可以指定其他格式来生成字符串。

DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMM dd, yyyy h:mm a z" );
String output = formatter.print( dateTimeToronto );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM