将时间戳解析为LocalDateTime [英] Parsing timestamp as LocalDateTime

查看:736
本文介绍了将时间戳解析为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

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

当我将字符串解析为<$ c $时c> 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()的值,

当您查看 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

在这种情况下,您需要始终使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆