JAVA8 LocalDateTime时间格式化

LocalDateTime转String

方法一:使用LocalDateTimeUtil工具类进行式化

LocalDateTime localDateTime = LocalDateTime.now();
String time =LocalDateTimeUtil.format(localDateTime,DatePattern.NORM_DATETIME_PATTERN);

其中:DatePattern类是日期格式化类,提供常用的日期格式化对象。

方法二:使用DateUtil工具类,需要导入hutool包

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.10</version>
        </dependency>
            LocalDateTime localDateTime = LocalDateTime.now();
            String time = DateUtil.format(localDateTime, "yyyyMMdd");

方法三:使用DateTimeFormatter格式化

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = LocalDateTime.now().format(df);

String转LocalDateTime

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.parse("2022-03-17 09:56:00", df);

//如果格式是yyyy-MM-dd,则使用LocalDate,使用LocalDateTime会报错:
//java.time.format.DateTimeParseException: Text '2022-03-17' could not be parsed: Unable to //obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2022-03-17 of type //java.time.format.Parsed
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate time = LocalDate.parse("2022-03-17", df);

注意:传入时间格式必须与格式化(df)格式一致,否则报错!

String时间类型转特定String时间类型

 DateTimeFormatter dfs = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
 LocalDateTime localDateTime = LocalDateTime.parse("2023-12-21T12:00:00.159+00:00",dfs);
 System.out.println(localDateTime);
 DateTimeFormatter dfa = DateTimeFormatter.ofPattern("yyyy-MM-dd");
 String format = localDateTime.format(dfa);
 System.out.println(format);
 //2023-12-21T12:00:00.159+00:00-->2023-12-21

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值