将时间戳解析为 LocalDateTime

Parsing timestamp as LocalDateTime(将时间戳解析为 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

基础教程推荐