我的时间以毫秒为单位,我需要将其转换为ZonedDateTime对象。
我有以下代码
long m = System.currentTimeMillis();
LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);
行
LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);
给我一个错误的说法 对于LocalDateTime类型,metheds millsToLocalDateTime未定义
答案 0 :(得分:2)
ZonedDateTime
和LocalDateTime
是different。
如果您需要LocalDateTime
,则可以按照以下方式进行操作:
long m = ...;
Instant instant = Instant.ofEpochMilli(m);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
答案 1 :(得分:2)
您可以立即创建一个ZonedDateTime
(使用系统区域ID):
//Instant is time-zone unaware, the below will convert to the given zone
ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m),
ZoneId.systemDefault());
如果您需要一个LocalDateTime
实例:
//And this date-time will be "local" to the above zone
LocalDateTime ldt = zdt.toLocalDateTime();
答案 2 :(得分:1)
是否要使用ZonedDateTime
,LocalDateTime
,OffsetDateTime
或LocalDate
,其语法实际上是相同的,并且都围绕着将毫秒应用于{{ 3}}首先使用Instant
。
long m = System.currentTimeMillis();
ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
OffsetDateTime odt = OffsetDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
LocalDate ld = LocalDate.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
打印它们会产生以下内容:
2018-08-21T12:47:11.991-04:00[America/New_York]
2018-08-21T12:47:11.991
2018-08-21T12:47:11.991-04:00
2018-08-21
打印Instant
本身会产生:
2018-08-21T16:47:11.991Z
答案 3 :(得分:0)
您不能在Java中创建扩展方法。如果要为此定义单独的方法,请创建一个Utility类:
class DateUtils{
public static ZonedDateTime millsToLocalDateTime(long m){
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = Instant.ofEpochSecond(m);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
return zonedDateTime;
}
}
通过您的其他课堂电话
DateUtils.millsToLocalDateTime(89897987989L);