如何从 Java 8 中的 LocalDateTime 获取毫秒数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23944370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get milliseconds from LocalDateTime in Java 8
提问by George Siggouroglou
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.
我想知道如果有一种方法,因为1970年1月1日(时期),以获得当前毫秒使用新的LocalDate
,LocalTime
或LocalDateTime
Java的8类。
The known way is below:
已知的方法如下:
long currentMilliseconds = new Date().getTime();
or
或者
long currentMilliseconds = System.currentTimeMillis();
采纳答案by Stuart Marks
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.
我不完全确定您所说的“当前毫秒”是什么意思,但我假设它是自“纪元”以来的毫秒数,即 UTC 时间 1970 年 1 月 1 日午夜。
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.
如果你想找到,因为时代的毫秒数眼下,然后用System.currentTimeMillis()
作为Anubian菜鸟指出。如果是这样,就没有理由使用任何新的 java.time API 来执行此操作。
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
从某个地方拥有一个或类似的对象,并且您想将其转换为自纪元以来的毫秒数。无法直接执行此操作,因为LocalDateTime
对象系列不知道它们所在的时区。因此,需要提供时区信息以查找相对于 UTC 的时代的时间。
Suppose you have a LocalDateTime
like this:
假设你有一个LocalDateTime
这样的:
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
. 我和洛杉矶在同一时区,所以我会做这样的事情:
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:
无论如何,如果你能得到一个 valid ZonedDateTime
,你可以将它转换为自纪元以来的毫秒数,如下所示:
long millis = zdt.toInstant().toEpochMilli();
回答by Anubian Noob
To get the current time in milliseconds (since the epoch), use System.currentTimeMillis()
.
要以毫秒为单位(自纪元以来)获取当前时间,请使用System.currentTimeMillis()
.
回答by brian
What I do so I don't specify a time zone is,
我这样做我没有指定时区是,
System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());
gives
给
ldt 1424812121078
ctm 1424812121281
As you can see the numbers are the same except for a small execution time.
如您所见,除了执行时间较短外,数字是相同的。
Just in case you don't like System.currentTimeMillis, use Instant.now().toEpochMilli()
以防万一您不喜欢 System.currentTimeMillis,请使用 Instant.now().toEpochMilli()
回答by Dani
To avoid ZoneId you can do:
为避免 ZoneId,您可以执行以下操作:
LocalDateTime date = LocalDateTime.of(1970, 1, 1, 0, 0);
System.out.println("Initial Epoch (TimeInMillis): " + date.toInstant(ZoneOffset.ofTotalSeconds(0)).toEpochMilli());
Getting 0 as value, that's right!
得到 0 作为值,没错!
回答by Marteng
Since Java 8 you can call java.time.Instant.toEpochMilli()
.
从 Java 8 开始,您可以调用java.time.Instant.toEpochMilli()
.
For example the call
例如调用
final long currentTimeJava8 = Instant.now().toEpochMilli();
gives you the same results as
给你相同的结果
final long currentTimeJava1 = System.currentTimeMillis();
回答by Nalam
You can use java.sql.Timestamp
also to get milliseconds.
您也可以使用java.sql.Timestamp
来获取毫秒。
LocalDateTime now = LocalDateTime.now();
long milliSeconds = Timestamp.valueOf(now).getTime();
System.out.println("MilliSeconds: "+milliSeconds);
回答by JeeBee
If you have a Java 8 Clock, then you can use clock.millis()
(although it recommends you use clock.instant()
to get a Java 8 Instant, as it's more accurate).
如果您有 Java 8 Clock,则可以使用clock.millis()
(尽管它建议您使用clock.instant()
Java 8 Instant,因为它更准确)。
Why would you use a Java 8 clock? So in your DI framework you can create a Clock bean:
为什么要使用 Java 8 时钟?所以在你的 DI 框架中你可以创建一个 Clock bean:
@Bean
public Clock getClock() {
return Clock.systemUTC();
}
and then in your tests you can easily Mock it:
然后在您的测试中,您可以轻松地模拟它:
@MockBean private Clock clock;
or you can have a different bean:
或者你可以有一个不同的bean:
@Bean
public Clock getClock() {
return Clock.fixed(instant, zone);
}
which helps with tests that assert dates and times immeasurably.
这有助于进行不可估量地断言日期和时间的测试。
回答by Mohamed.Abdo
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();
}
回答by maxxyme
Why didn't anyone mentioned the method LocalDateTime.toEpochSecond()
:
为什么没有人提到方法LocalDateTime.toEpochSecond()
:
LocalDateTime localDateTime = ... // whatever e.g. LocalDateTime.now()
long time2epoch = localDateTime.toEpochSecond(ZoneOffset.UTC);
This seems way shorter that many suggested answers above...
这似乎比上面的许多建议答案要短得多......