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

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

问题描述

我想知道是否有办法从1-1-1970(epoch)获取当前的毫秒,使用新的 LocalDate LocalTime LocalDateTime Java 8的类。



已知的方法如下:

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

  long currentMilliseconds = System.currentTimeMillis(); 


解决方案

我不完全确定你的意思是当前毫秒,但我认为这是自纪元以来的毫秒数,即1970年1月1日星期五UTC。



如果您想查找号码然后使用 System.currentTimeMillis()作为。如果是这样,没有理由使用任何新的java.time API来执行此操作。



但是,也许您已经有一个 LocalDateTime 或类似的对象,你想要将它转换为从时代以来的毫秒。不可能直接做到这一点,因为 LocalDateTime 对象系列没有任何时间区域的概念。因此,需要提供时区信息来查找相对于时代的时间是UTC。



假设你有一个 LocalDateTime ,这样:

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

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

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

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



无论如何,如果你可以得到一个有效的 ZonedDateTime ,您可以将其转换为自时代以来的毫秒数,如下所示:

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


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.

The known way is below:

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

or

long currentMilliseconds = System.currentTimeMillis();

解决方案

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.

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.

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.

Suppose you have a LocalDateTime like this:

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

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.

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天全站免登陆