如何从 Java 8 中的 LocalDateTime 获取毫秒 [英] How to get milliseconds from LocalDateTime in Java 8

查看:108
本文介绍了如何从 Java 8 中的 LocalDateTime 获取毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法使用新的 LocalDateLocalTimeLocalDateTime<获取自 1-1-1970(纪元)以来的当前毫秒数/code> Java 8 类.

I am wondering if there is a way to get current milliseconds since 1-1-1970 (epoch) using the new LocalDate, LocalTime or LocalDateTime classes of Java 8.

已知方式如下:

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

long currentMilliseconds = System.currentTimeMillis();

推荐答案

我不完全确定你所说的当前毫秒"是什么意思,但我假设它是自纪元"以来的毫秒数,即午夜,UTC 时间 1970 年 1 月 1 日.

I'm not entirely sure what you mean by "current milliseconds" but I'll assume it's the number of milliseconds since the "epoch," namely midnight, January 1, 1970 UTC.

如果你想现在找到自纪元以来的毫秒数,然后使用 System.currentTimeMillis() 作为 阿努比亚菜鸟指出.如果是这样,就没有理由使用任何新的 java.time API 来执行此操作.

If you want to find the number of milliseconds since the epoch right now, then use System.currentTimeMillis() as Anubian Noob has pointed out. If so, there's no reason to use any of the new java.time APIs to do this.

但是,也许您已经有一个 LocalDateTime 或来自某处的类似对象,并且您想将其转换为自纪元以来的毫秒数.不能直接这样做,因为 LocalDateTime 对象系列不知道它们所在的时区.因此需要提供时区信息来查找相对于纪元的时间,这是在UTC.

However, maybe you already have a LocalDateTime or similar object from somewhere and you want to convert it to milliseconds since the epoch. It's not possible to do that directly, since the LocalDateTime family of objects has no notion of what time zone they're in. Thus time zone information needs to be supplied to find the time relative to the epoch, which is in UTC.

假设你有一个这样的 LocalDateTime:

Suppose you have a LocalDateTime like this:

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

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

You need to apply the time zone information, giving a ZonedDateTime. I'm in the same time zone as Los Angeles, so I'd do something like this:

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

当然,这是对时区的假设.并且存在可能发生的边缘情况,例如,如果本地时间恰好命名为接近夏令时(夏令时)转换的时间.让我们把这些放在一边,但你应该知道这些情况是存在的.

Of course, this makes assumptions about the time zone. And there are edge cases that can occur, for example, if the local time happens to name a time near the Daylight Saving Time (Summer Time) transition. Let's set these aside, but you should be aware that these cases exist.

无论如何,如果你能得到一个有效的ZonedDateTime,你可以将它转换为自纪元以来的毫秒数,如下所示:

Anyway, if you can get a valid ZonedDateTime, you can convert this to the number of milliseconds since the epoch, like so:

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

这篇关于如何从 Java 8 中的 LocalDateTime 获取毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆