DateStyle日期时间字符串序列化

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

import static java.time.temporal.ChronoField.*;

public class DataStyle {

    public static DateTimeFormatter DATE_SERIALIZATION = new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR)
            .optionalStart()
            .appendLiteral('-')
            .optionalEnd()
            .optionalStart()
            .appendLiteral('/')
            .optionalEnd()
            .appendValue(ChronoField.MONTH_OF_YEAR)
            .optionalStart()
            .appendLiteral('-')
            .optionalEnd()
            .optionalStart()
            .appendLiteral('/')
            .optionalEnd()
            .appendValue(ChronoField.DAY_OF_MONTH)
            .toFormatter();

    public static DateTimeFormatter TIME_SERIALIZATION = new DateTimeFormatterBuilder()
            .appendValue(HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(MINUTE_OF_HOUR, 2)
            .appendLiteral(':')
            .appendValue(SECOND_OF_MINUTE, 2)
            .optionalStart()
            .appendFraction(NANO_OF_SECOND, 0, 9, true)
            .optionalEnd()
            .toFormatter();

    // 日期时间序列化 外部序列化为LocalDateTime 或LocalDate时使用
    public static DateTimeFormatter DATE_TIME_SERIALIZATION = new DateTimeFormatterBuilder()
            .append(DATE_SERIALIZATION)
            .optionalStart()
            .appendLiteral(' ')
            .optionalEnd()
            .optionalStart()
            .appendLiteral('T')
            .optionalEnd()
            .append(TIME_SERIALIZATION)
            .toFormatter();

    // 日期转换为日期字符串, 不存在分隔符
    public static DateTimeFormatter DATE_NUMBER = new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR)
            .appendValue(ChronoField.MONTH_OF_YEAR, 2)
            .appendValue(ChronoField.DAY_OF_MONTH, 2)
            .toFormatter();

    // 时间转换为时间字符串, 不存在分隔符
    public static DateTimeFormatter TIME_NUMBER = new DateTimeFormatterBuilder()
            .appendValue(HOUR_OF_DAY, 2)
            .appendValue(MINUTE_OF_HOUR, 2)
            .appendValue(SECOND_OF_MINUTE, 2)
            .appendFraction(NANO_OF_SECOND, 0, 9, false)
            .toFormatter();

    // 日期时间转换为日期时间字符串, 不存在分隔符
    public static DateTimeFormatter DATE_TIME_NUMBER = new DateTimeFormatterBuilder()
            .append(DATE_NUMBER)
            .append(TIME_NUMBER)
            .toFormatter();


    public static DateTimeFormatter ISO_DATE = DateTimeFormatter.ISO_DATE;
    public static DateTimeFormatter ISO_TIME = DateTimeFormatter.ISO_TIME;
    public static DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME;

}

posted @ 2025-10-04 15:18  br-vst  阅读(4)  评论(0)    收藏  举报