我想知道是否有一种方法可以使用Java 8的新的LocalDate, LocalTime或LocalDateTime类来获取自1-1-1970 (epoch)以来的当前毫秒。

已知的方法如下:

long currentMilliseconds = new Date().getTime();

or

long currentMilliseconds = System.currentTimeMillis();

当前回答

要获得以毫秒为单位的当前时间(从epoch开始),请使用System.currentTimeMillis()。

其他回答

我认为这个更简单:

ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault());
Assert.assertEquals(System.currentTimeMillis(), zdt.toInstant().toEpochMilli());

获取类似System.currentTimeMillis()(从UTC)的millis。

我不完全确定您所说的“当前毫秒”是什么意思,但我假设它是自“epoch”(即UTC 1970年1月1日午夜)以来的毫秒数。

如果您想要找到当前纪元以来的毫秒数,那么使用System.currentTimeMillis(),就像Anubian Noob指出的那样。如果是这样,就没有理由使用任何新的java了。time api来做这个。

但是,也许您已经从某个地方获得了LocalDateTime或类似对象,并且希望将其转换为自epoch以来的毫秒数。这是不可能直接做到的,因为LocalDateTime对象家族不知道它们所在的时区。因此,需要提供时区信息来查找相对于epoch的时间,即UTC时间。

假设你有一个这样的LocalDateTime:

LocalDateTime ldt = LocalDateTime.of(2014, 5, 29, 18, 41, 16);

您需要应用时区信息,给出一个ZonedDateTime。我和洛杉矶在同一个时区,所以我会这样做:

ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));

当然,这需要对时区进行假设。也有可能出现一些边缘情况,例如,如果当地时间恰好命名为接近日光节约时间(夏季时间)过渡的时间。我们先把这些放在一边,但你应该知道这些情况是存在的。

不管怎样,如果你能得到一个有效的ZonedDateTime,你可以把它转换成从epoch开始的毫秒数,像这样:

long millis = zdt.toInstant().toEpochMilli();

我在不指定时区的情况下,

System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());

给了

ldt 1424812121078 
ctm 1424812121281

正如你所看到的,数字是相同的,除了一个小的执行时间。

以防你不喜欢系统。currentTimeMillis,使用Instant.now().toEpochMilli()

  default LocalDateTime getDateFromLong(long timestamp) {
    try {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC);
    } catch (DateTimeException tdException) {
      //  throw new 
    }
}

default Long getLongFromDateTime(LocalDateTime dateTime) {
    return dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
}

你可以试试这个:

long diff = LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();