更新时间:2023-11-30 11:02:40
DateTimeFormatter desiredFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
String truncatedDateTimeString = "2017-06-05T19:27";
LocalDateTime dateTime = LocalDateTime.parse(truncatedDateTimeString);
String fixedDateTimeString = dateTime.format(desiredFormatter);
System.out.println(fixedDateTimeString);
此打印
2017-06-05T19:27:00.000000
2017-06-05T19:27:00.000000
如果还缺少分钟和小时,那么我们还需要更多技巧.查看 DateTimeFormatterBuilder
及其 parseDefaulting
方法.在格式模式字符串中使用方括号 []
包围可能缺少的部分.我不确定如果小时数被截断,您的字符串会是什么样子? T
也会丢失吗?
If also the minutes and hours are missing, we need some more trickery, though. Look into DateTimeFormatterBuilder
and its parseDefaulting
method. Use square brackets []
in the format pattern string to surround the parts that may be missing. I am not sure what your string will look like if the hours have been truncated — will the T
be missing too?
另一方面,如果字符串为 2017-06-05T19:27:10.917360
,上述方法同样适用,在这种情况下,只需将相同的字符串打印回去即可.
On the other hand the above also works if the string was 2017-06-05T19:27:10.917360
, and in this case just prints the same string back.
我也不确定您真正要解决的问题.尾随零是多余的,那么将其截断是什么问题?
Also I am not sure which problem you are really trying to solve. Trailing zeroes are redundant, so what is the problem in them being truncated?
以下方法完善了我对 DateTimeFormatterBuilder
,其 parseDefaulting
方法和格式模式字符串中的方括号所说的内容:
The following method fleshes out what I said about DateTimeFormatterBuilder
, its parseDefaulting
method and square brackets in the format pattern string:
public static String addTrailingZerosToTimestamp(String timeStamp) {
DateTimeFormatter truncatedFormatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd['T'HH[:mm[:ss[.SSSSSS]]]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.toFormatter();
DateTimeFormatter desiredFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, truncatedFormatter);
return dateTime.format(desiredFormatter);
}
它与 2017-06-05
, 2017-06-05T19
, 2017-06-05T19:27
,2017-06-05T19:27:10
和 2017-06-05T19:27:10.917360
,但不适用于 2017-06-05T19:27:10.917
It works with 2017-06-05
, 2017-06-05T19
, 2017-06-05T19:27
, 2017-06-05T19:27:10
and 2017-06-05T19:27:10.917360
, but not with 2017-06-05T19:27:10.917
.