Java 8 LocalDateTime - 如何在字符串转换中保持 .000 毫秒
Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion
我有一个通过 String
收到的时间戳,格式如下:
2016-10-17T12:42:04.000
我正在通过以下行将其转换为 LocalDateTime
以增加一些天数(然后返回到 String
):
String _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")).minusDays(120).toString());
但是,我注意到它返回的响应减少了 .000
毫秒。
我不确定确保保留准确模式的最简洁方法。现在我只是添加一个毫秒,可能有一种方法可以将旧的 SimpleDateFormat
合并到其中,但我希望有更好的方法。
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.
使用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));
我有一个通过 String
收到的时间戳,格式如下:
2016-10-17T12:42:04.000
我正在通过以下行将其转换为 LocalDateTime
以增加一些天数(然后返回到 String
):
String _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")).minusDays(120).toString());
但是,我注意到它返回的响应减少了 .000
毫秒。
我不确定确保保留准确模式的最简洁方法。现在我只是添加一个毫秒,可能有一种方法可以将旧的 SimpleDateFormat
合并到其中,但我希望有更好的方法。
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.
使用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));