首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用DateTimeFormatterBuilder解析LocalDateTime短年格式dd-mm-YY HH:mm

DateTimeFormatterBuilder是Java 8中的一个类,用于构建自定义的日期时间格式化器。它提供了一种灵活的方式来解析和格式化日期时间对象。

在给定的问答内容中,我们需要使用DateTimeFormatterBuilder来解析一个短年格式的LocalDateTime对象,格式为dd-mm-YY HH:mm。

首先,我们需要创建一个DateTimeFormatterBuilder对象,并使用其方法来定义日期时间格式。在这种情况下,我们需要使用两个字段:日和月,以及两个时间字段:小时和分钟。

以下是一个示例代码,演示如何使用DateTimeFormatterBuilder来解析短年格式的LocalDateTime对象:

代码语言:java
复制
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;

public class DateTimeParsingExample {
    public static void main(String[] args) {
        String dateTimeString = "01-02-21 12:34";

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("dd-MM-")
                .appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, 2000)
                .appendPattern(" HH:mm")
                .toFormatter()
                .withResolverStyle(ResolverStyle.STRICT);

        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);

        System.out.println(dateTime);
    }
}

在上述代码中,我们首先定义了一个日期时间字符串dateTimeString,它符合短年格式dd-mm-YY HH:mm。

然后,我们创建了一个DateTimeFormatterBuilder对象,并使用appendPattern方法来添加日期和时间的格式。appendValueReduced方法用于将年份字段缩减为两位数,并指定了缩减的范围和基准年份。最后,我们使用toFormatter方法将DateTimeFormatterBuilder对象转换为DateTimeFormatter对象,并使用withResolverStyle方法设置解析器的解析样式为STRICT。

最后,我们使用LocalDateTime.parse方法将日期时间字符串解析为LocalDateTime对象,并将结果打印出来。

这是一个完整的示例,展示了如何使用DateTimeFormatterBuilder解析短年格式的LocalDateTime对象。在实际应用中,您可以根据需要进行适当的调整和扩展。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券