DateTimeFormatter:格式化或解析日期、时间

这篇博客详细介绍了Java 8中LocalDateTime的使用,包括预定义格式、本地化格式和自定义格式的日期时间格式化和解析,展示了如何将日期时间转换为字符串以及反向解析字符串到日期时间。

代码如下:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

public class StartApplication {
    public static void main(String[] args) {


        //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISo_LOCAL_TIME
        DateTimeFormatter isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        //格式化-->日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        String str = isoLocalDateTime.format(localDateTime);
        System.out.println(str);

        //解析:字符串-->日期
        TemporalAccessor parse = isoLocalDateTime.parse("2022-05-10T16:18:03.676");
        System.out.println(parse);


        //方式二:
        //本地化相关的格式。如:ofLocalizedDateTime()
        // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String format = dateTimeFormatter.format(localDateTime);
        System.out.println(format);

        //本地化相关的格式。如:ofLocalizedDate()
        //FormatStyle.FULL / FormatStyle.LONG /FormatStyle.MEDIUM / FormatStyle.SHORT:适用于LocalDate
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        //格式化
        String format1 = dateTimeFormatter1.format(LocalDateTime.now());
        System.out.println(format1);


        //方式三:自定义的格式。如: ofPattern("yyyy-MM-dd hh:mm:ss E")
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format2 = dateTimeFormatter2.format(LocalDateTime.now());
        System.out.println(format2);
        //解析
        TemporalAccessor parse1 = dateTimeFormatter2.parse("2022-05-10 04:38:19");
        System.out.println(parse1);

    }
}

结果如下:

2022-05-10T16:40:08.432
2022-05-10T16:40:08.432
{},ISO resolved to 2022-05-10T16:18:03.676
2022年5月10日 下午04时40分08秒
2022年5月10日 星期二
2022-05-10 04:40:08
{HourOfAmPm=4, NanoOfSecond=0, MinuteOfHour=38, MilliOfSecond=0, SecondOfMinute=19, MicroOfSecond=0},ISO resolved to 2022-05-10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值