問題描述
我想將 yyyy-MM-dd'T'HH:mm:ss
形式的時間戳解析為 LocalDateTime
.這樣做時,如果它們是 00
,它會去除秒數(shù).
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
當(dāng)我將字符串解析為 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?
推薦答案
你應(yīng)該期待兩者之間的輸出差異
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()
的值,預(yù)計(jì)不會產(chǎn)生與您的模式相同的輸出.
System.out.println(dateLDT);
prints the value of dateLDT.toString()
, which is not expected to produce the same output as your pattern.
當(dāng)您查看 LocalDateTime.toString()
時,您會看到它將時間部分委托給 LocalTime.toString()
,它有條件地打印秒數(shù):
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.
這篇關(guān)于將時間戳解析為 LocalDateTime的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!