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
Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion
提问by daniel9x
I have a timestamp that I receive via a String
in the following format:
我有一个通过String
以下格式接收的时间戳:
2016-10-17T12:42:04.000
2016-10-17T12:42:04.000
I am converting it to a LocalDateTime
to add some days to it (then back to a String
) via the following line:
我将它转换为 aLocalDateTime
以String
通过以下行为其添加几天(然后返回到 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 .000
milliseconds.
但是,我注意到它返回的响应减少了.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 SimpleDateFormat
into 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));