如何从以毫秒为单位的长纪元时间创建 Java 8 LocalDate?

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

我有一个外部 API,returns 我的日期是 longs,表示为自纪元开始以来的毫秒数。

使用旧样式 Java API,我会简单地从中构建一个 Date

Date myDate = new Date(startDateLong)

Java 8 的等价物是什么 LocalDate/LocalDateTime 类?

我有兴趣将 long 表示的时间点转换为我当前本地时区的 LocalDate

您可以从 Instant.ofEpochMilli(long):

开始
LocalDate date =
  Instant.ofEpochMilli(startDateLong)
  .atZone(ZoneId.systemDefault())
  .toLocalDate();

如果您有自大纪元以来的毫秒数,并希望使用当前本地时区将它们转换为本地日期,您可以使用

LocalDate date =
    Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();

但请记住,即使是系统的默认时区也可能会发生变化,因此相同的 long 值可能会在后续运行中产生不同的结果,即使在同一台机器上也是如此。

此外,请记住 LocalDatejava.util.Date 不同,它真正代表的是日期,而不是日期和时间。

否则,您可以使用 LocalDateTime:

LocalDateTime date =
    LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());

撇开时区和其他因素,new Date(startDateLong) 的一个非常简单的替代方案可能是 LocalDate.ofEpochDay(startDateLong / 86400000L)

我想我有更好的答案。

new Timestamp(longEpochTime).toLocalDateTime();

在特定情况下,您的纪元秒时间戳来自 SQL 或与 SQL 有某种关联,您可以这样获取:

long startDateLong = <...>

LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();

将 now.getTime() 替换为您的长值。

//GET UTC time for current date
        Date now= new Date();
        //LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

我不太喜欢在项目中同时使用 instant 和 localdate。

我会做什么:

 val calendar = Calendar.getInstance().apply {
    //set timeZone because calendar.timeInMillis = UTC milliseconds
    //and calender uses the default timezone
    timeZone = TimeZone.getTimeZone("UTC")
 }
 calendar.clear()
 calendar.set(localDate.year, localDate.monthValue - 1, localDate.dayOfMonth)
 val millis = calendar.timeInMillis

基于的简单版本:

LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(epochMillis).toDays());