在 java.time (Java 8) 中正确地将时间转换为毫秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28466845/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:17:50  来源:igfitidea点击:

Converting a time to milliseconds correctly in java.time (Java 8)

javadatejava-8java-time

提问by Seagull

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. The following is something I tried

但我一直无法正确地做到这一点。我正在尝试将“29/Jan/2015:18:00:00”转换为毫秒。以下是我尝试过的

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. I am not saying this is the best way to do this, if you know something better, I would really appreciate some pointers.

我尝试使用LocalDateTime,但找不到有效地将转换为毫秒的方法。我并不是说这是最好的方法,如果你知道更好的东西,我真的很感激一些指示。

采纳答案by Jeffrey

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 个位置。

回答by MadProgrammer

From Date and Time Classesthe 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

回答by Seagull

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