[英]Converting a time to milliseconds correctly in java.time (Java 8)
I've been trying to convert a "DateTime" to milliseconds using the java.time package built into Java 8. 我一直在尝试使用Java 8中内置的java.time包将“DateTime”转换为毫秒。
But I haven't been able to do it correctly. 但我无法正确地做到这一点。 I am trying to convert "29/Jan/2015:18:00:00" to milliseconds. 我想将“29 / Jan / 2015:18:00:00”转换为毫秒。 The following is something I tried 以下是我尝试过的
Instant instant = Instant.parse("2015-01-29T18:00:00.0z");
Long instantMilliSeconds = Long.parseLong(instant.getEpochSecond() + "" + instant.get(ChronoField.MILLI_OF_SECOND));
System.out.println(new Date(instantMilliSeconds)); // prints Sun Jun 14 05:06:00 PDT 1970
I tried using LocalDateTime
, but couldn't find a way to effectively do the conversion to milliseconds. 我尝试使用LocalDateTime
,但找不到有效转换为毫秒的方法。 I am not saying this is the best way to do this, if you know something better, I would really appreciate some pointers. 我并不是说这是最好的方法,如果你知道更好的东西,我会非常感谢一些指示。
You should use Instant::toEpochMilli
. 你应该使用Instant::toEpochMilli
。
System.out.println(instant.toEpochMilli());
System.out.println(instant.getEpochSecond());
System.out.println(instant.get(ChronoField.MILLI_OF_SECOND));
prints 版画
1422554400000
1422554400
0
Your version did not work because you forgot to pad instant.get(ChronoField.MILLI_OF_SECOND)
with extra zeros to fill it out to 3 places. 您的版本无效,因为您忘记使用额外的零填充instant.get(ChronoField.MILLI_OF_SECOND)
以将其填充到3个位置。
From Date and Time Classes the tutorials... 从日期和时间课程教程......
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss");
LocalDateTime date = LocalDateTime.parse("29/Jan/2015:18:00:00", formatter);
System.out.printf("%s%n", date);
Prints 2015-01-29T18:00
打印2015-01-29T18:00
ZoneId id = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.of(date, id);
System.out.println(zdt.toInstant().toEpochMilli());
Prints 1422514800000
打印1422514800000
Okay, I think I finally found an easy way to do what I am trying to do 好吧,我想我终于找到了一种简单的方法来做我想做的事情
LocalDateTime localDateTime = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("dd/MMM/uuuu:H:m:s"));
System.out.println(localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli());
Prints 1390903200000 打印1390903200000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.