Java 8 LocalDateTime - 如何在字符串转换中保持 .000 毫秒

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

Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion

javadatetimeformatdatetime-formatjava-time

提问by daniel9x

I have a timestamp that I receive via a Stringin the following format:

我有一个通过String以下格式接收的时间戳:

2016-10-17T12:42:04.000

2016-10-17T12:42:04.000

I am converting it to a LocalDateTimeto add some days to it (then back to a String) via the following line:

我将它转换为 aLocalDateTimeString通过以下行为其添加几天(然后返回到 a ):

String _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000",
    DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")).minusDays(120).toString());

However, I noticed that the response it gives back drops the .000milliseconds.

但是,我注意到它返回的响应减少了.000毫秒。

I'm not sure the cleanest way to ensure that the exact pattern is preserved. For now I'm just adding a single millisecond, and there's probably a way to incorporate the old SimpleDateFormatinto it, but I was hoping there's an even better way.

我不确定确保保留确切模式的最干净方法。现在我只是添加一个毫秒,可能有一种方法可以将旧的SimpleDateFormat合并到其中,但我希望有更好的方法。

回答by Ward

LocalDateTime::toStringomits parts if zero:

LocalDateTime::toString如果为零则省略部分:

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

所使用的格式将是输出完整时间值的最短格式,其中省略部分暗示为零。

Use LocalDateTime::formatinstead of relying on toString().

使用LocalDateTime::format而不是依赖toString().

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000", formatter).minusDays(120);

// This just uses default formatting logic in toString. Don't rely on it if you want a specific format.
System.out.println(_120daysLater.toString());

// Use a format to use an explicitly defined output format
System.out.println(_120daysLater.format(formatter));