我想将 yyyy-MM-dd'T'HH:mm:ss 形式的时间戳解析为 LocalDateTime.这样做时,如果它们是 00,它会去除秒数.
I want to parse a timestamp in the form of yyyy-MM-dd'T'HH:mm:ss as LocalDateTime. When doing so, it strips the seconds if they are 00.
如此处所述,我需要使用自定义格式化程序
As described here, I need to use a custom formatter
LocalDateTime date = LocalDateTime.parse("2008-10-02T12:30:00");
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
String dateString = date.toString();
String dateFormatted = date.format(f);
System.out.println(dateString); // 2008-10-02T12:30
这个可行,但它返回一个 String:
This one works, but it returns a String:
System.out.println(dateFormatted); // 2008-10-02T12:30:00
当我将字符串解析为 LocalDateTime 时,它会再次剥离 00:
When I parse the string to LocalDateTime it strips the 00 again:
LocalDateTime dateLDT = LocalDateTime.parse(dateFormatted, f);
System.out.println(dateLDT); // 2008-10-02T12:30
那么如何将日期解析为 LocalDateTime,而不是 String,并在末尾保留 00?
So how can I parse a date as LocalDateTime, instead of String, and keep the 00 at the end?
你应该期待两者之间的输出差异
You should expect a difference in output between
LocalDateTime dateLDT = LocalDateTime.parse(dateFormatted, f);
System.out.println(dateLDT);
还有
System.out.println(dateLDT.format(f)) //or f.format(dateLDT)
System.out.println(dateLDT); 打印 dateLDT.toString() 的值,预计不会产生与您的模式相同的输出.
System.out.println(dateLDT); prints the value of dateLDT.toString(), which is not expected to produce the same output as your pattern.
当您查看 LocalDateTime.toString() 时,您会看到它将时间部分委托给 LocalTime.toString(),它有条件地打印秒数:
When you look at LocalDateTime.toString(), you'll see that it delegates the time part to LocalTime.toString(), which prints seconds conditionally:
public String toString() {
...
if (secondValue > 0 || nanoValue > 0) {
buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
...
}
}
return buf.toString();
}
如果它的值为0,它只是省略秒字段.
It simply omits the seconds field if its value is 0.
在这种情况下,如果您必须确定输出/输入格式,您需要始终使用 DateTimeFormatter 来格式化您的日期.
What you need to do in this case is always use a DateTimeFormatter to format your date if you have to be certain about the output/input format.
这篇关于将时间戳解析为 LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
解析 ISO 8601 字符串本地日期时间,就像在 UTC 中Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期时间,就像在 UTC 中一样)
如何将公历字符串转换为公历?How to convert Gregorian string to Gregorian Calendar?(如何将公历字符串转换为公历?)
Java:GregorianCalendar 的最大值和最小值是什么/在哪Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
1582 年 10 月 15 日之前日期的日历到日期转换.公历Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日历到日期转换
java日历setFirstDayOfWeek不起作用java Calendar setFirstDayOfWeek not working(java日历setFirstDayOfWeek不起作用)
Java:获取当前星期几的值Java: getting current Day of the Week value(Java:获取当前星期几的值)