【问题标题】:Converting a date from long format to LocalDateTime format in Java 8 [duplicate]在Java 8中将日期从长格式转换为LocalDateTime格式[重复]
【发布时间】:2019-05-06 19:01:55
【问题描述】:

我正在使用 java 8,并且我有一个方法可以接受长格式参数的日期并从 java.time.LocalDateTime 库返回 LocalDateTime 中的日期。

在使用 java.util.Date,但现在我需要使用 java.time.LocalDateTime,但我找不到有关如何从 long 值转换为 LocalDateTime 的文档。

之前:

public Date setDate (long ldate){

  Date newDate = new Date(ldate);

  return newDate;
}

现在:

public LocalDateTime setDate(long ldate){

  LocalDateTime newDate;

  //{convert from long to LocalDateTime}

  return newDate
}

感谢您的帮助!

【问题讨论】:

  • @ernest_k 我想这可能就是我要找的东西,请你解释一下纪元时间是多少?
  • 查看此维基百科页面:en.wikipedia.org/wiki/Unix_time(在您的情况下,ldate 是自纪元以来的毫秒数)
  • LocalDateTime 是完全错误的类。阅读它的类 JavaDoc。暂时使用InstantOffsetDateTimeZonedDateTime

标签: datetime java-8 java-time localdate


【解决方案1】:

你可以如何实现LocalDateTime这样的方法:

public LocalDateTime setDate(long ldate){

        Date dateLong = new Date(ldate);    
        Instant instant = dateLong.toInstant();
        ZoneId defaultZoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(defaultZoneId).toLocalDateTime();
        return localDateTime;
}

【讨论】:

  • 没有必要将糟糕的遗留类Date 与现代的java.time 类混合在一起。请参阅Instant.ofEpoch… 方法。
  • LocalDateTime 是这里的错误类。该类丢弃了有价值的时区信息。请改用ZonedDateTime
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2021-12-09
  • 2015-09-30
相关资源
最近更新 更多