Java如何将UTC毫秒转换成UTC日期

标签 java utc

我有一个 int 1446159600,它是 UTC/GMT 日期,星期四,2015 年 10 月 29 日 23:00:00 GMT。我尝试转换为实际的 UTC 日期,但无法使其与 Calendar、SimpleDateFormat 和 Timezone 类一起使用。有人可以帮助我吗?

最佳答案

到;博士

Instant.ofEpochSecond ( 1_446_159_600L )

2015-10-29T23:00:00Z

从纪元开始计数

您似乎有一个整数 count-from- epochUnix time 的纪元计算整秒, 1970 年的第一刻 UTC .

您引用的旧日期时间类基于毫秒。所以乘以 1,000。

java.time

更好的是,完全避免那些旧类(class)。新java.time Java 8 及更高版本中的框架是一个巨大的改进,取代了那些旧的类。参见 Tutorial .这些新类的分辨率为 nanoseconds , 或几分之一秒内的 9 位小数。

Instant类(UTC 时间轴上的一个时刻)甚至有一个方便的 ofEpochSecond方法,所以不需要乘以一千。

long wholeSecondsFromEpochInUtc = 1_446_159_600L;
Instant instant = Instant.ofEpochSecond ( wholeSecondsFromEpochInUtc );

这一次性解决了您的问题。

格式化

我们可以走得更远。对该 Instant 应用时区以获得 ZonedDateTime .

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL ).withLocale ( Locale.CANADA_FRENCH );
String output = zdt.format ( formatter );

转储到控制台。

System.out.println ( "instant (UTC): " + instant );
System.out.println ( "zdt: " + zdt );
System.out.println ( "output: " + output );

instant (UTC): 2015-10-29T23:00:00Z

zdt: 2015-10-29T19:00-04:00[America/Montreal]

output: jeudi 29 octobre 2015 19 h 00 EDT

关于Java如何将UTC毫秒转换成UTC日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33430787/

相关文章:

java - PowerMock 访问私有(private)成员

java - Protobuf + java java.lang.IndexOutOfBoundsException : Invalid index 0, 大小为 0

python - 如何使用 python 获取 UTC 日期时间、自动检测用户时区并将日期时间转换为所需格式?

iphone - 尝试从祖鲁时间的 UTC 字符串获取日期时为 Nil NSDate

swift - 需要将 UTC 时间转换为设备的当前时区

java - 调试时无法实例化 Activity 问题

java - @LazyCollection(LazyCollectionOption.FALSE) 和@OneToMany(fetch = FetchType.EAGER) 之间的区别

java - 什么是NullPointerException,我该如何解决?

mysql - mysql datetime 中 utc 时间的表示不正确

javascript - 如何使用 JavaScript 获取 UTC 日期?