localdatetime获得时间搓_将时间戳解析为LocalDateTime

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

This one works, but it returns a String:

System.out.println(dateFormatted); // 2008-10-02T12:30: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

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);

And

System.out.println(dateLDT.format(f)) //or f.format(dateLDT)

System.out.println(dateLDT); prints the value of dateLDT.toString(), which is not expected to produce the same output as your pattern.

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();

}

It simply omits the seconds field if its value is 0.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值