将时间戳解析为 LocalDateTime

我想以yyyy-MM-dd'T'HH:mm:ssas的形式解析时间戳LocalDateTime。这样做时,如果它们是 ,它会删除秒数00。


如此处所述,我需要使用自定义格式化程序


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:


System.out.println(dateFormatted); // 2008-10-02T12:30:00

当我将字符串解析为LocalDateTime它时,它会再次剥离00:


LocalDateTime dateLDT = LocalDateTime.parse(dateFormatted, f);

System.out.println(dateLDT); // 2008-10-02T12:30

那么如何将日期解析为LocalDateTime, 而不是String, 并保留00在末尾?


一只萌萌小番薯
浏览 217回答 2
2回答

子衿沉夜

您应该期望输出之间的差异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(),预计不会产生与您的模式相同的输出。当您查看 时LocalDateTime.toString(),您会看到它将时间部分委托给LocalTime.toString(),它有条件地打印秒数:public String toString() {&nbsp; &nbsp; ...&nbsp; &nbsp; if (secondValue > 0 || nanoValue > 0) {&nbsp; &nbsp; &nbsp; &nbsp; buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return buf.toString();}如果它的值为 ,它只是省略了 seconds 字段0。DateTimeFormatter如果您必须确定输出/输入格式,在这种情况下您需要做的是始终使用 a来格式化您的日期。

慕慕森

每个日期对象都有秒。它是否选择使用默认toString实现来显示它们并不重要。如果你想要一个特定的格式,你总是需要使用格式化程序。如果您想查看秒数,请使用适当的格式化程序或设置断点并检查对象。查看任何东西的任何实现&nbsp;toString都不能保证显示任何有用的东西或代表实际的对象状态。该对象可以只返回一个随机日期字符串。现在你可以使用date,它非常好,它有几秒钟。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java