Parsing timestamp as LocalDateTime(将时间戳解析为 LocalDateTime)
问题描述
我想将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将时间戳解析为 LocalDateTime
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
