SimpleDateFormat进阶LocalDate,LocalTime,LocalDateTime的简单demo

代码
public class Test {
    public static void main(String[] args) {
        /**
         * String转为时间日期格式
         */
        //String转换为localDate
        LocalDate localDate = LocalDate.parse("2022-04-18");
        DateTimeFormatter patter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        System.out.println(localDate);
        System.out.println(LocalDate.parse("2022-04-18").format(patter));
        //String转换为LocalTime
        LocalTime localTime = LocalTime.parse("14:45:45");
        //String转换为LocalDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");//12小时格式时间
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//24小时格式时间
        LocalDate localDate1 = LocalDate.parse("2022-04-18 14:54:56",formatter1);
        System.out.println(localTime);
        System.out.println(localDate1);

        /**
         * 时间转为String
         */
        //LocalDate转为String
        LocalDate localDate2 = LocalDate.now();
        String formate1 = localDate2.format(DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(localDate2);
        System.out.println(formate1);

        //LocalTime转为String
        LocalTime localTime1 = LocalTime.now();
        String format3 = localTime1.format(DateTimeFormatter.ISO_TIME);
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss");
        String format4 = localTime1.format(formatter2);
        System.out.println(format3);
        System.out.println(format4);

        //LocalDateTime转为String
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String format5 = localDateTime.format(formatter3);
        System.out.println(format5);

    }
}

输出结果:

2022-04-18
2022年04月18日
14:45:45
2022-04-18
2022-04-18
20220418
15:25:19.869
03:25:19
2022-04-18 03:25:19

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值