DateTimeFormatter、SimpleDateFormat实现时间格式化

public class DateTimeFormatterTest {
    public static void main(String[] args) {
        //利用SimpleDateFormat和Date搭配进行日期时间转换  Date -> Text
        SimpleDateFormat sdf1 = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
        Date date1 = new Date();
        String format1 = sdf1.format(date1);
        System.out.println(format1);

        //利用SimpleDateFormat和Date搭配进行日期时间转换  Text -> Date SimpleDateFormat参与应与需要转换的字符串相对应
        String time2 = "21/10/19 19:47:53";
        SimpleDateFormat myFmt2 = new SimpleDateFormat("yy/MM/dd HH:mm");
        Date date2 = null;
        try {
            date2 = myFmt2.parse(time2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date2.toString());

        //利用SimpleDateFormat和Date搭配进行日期时间转换  Text -> Date  SimpleDateFormat参与应与需要转换的字符串相对应
        String time3 = "2018年06月19日 23时10分";
        SimpleDateFormat myFmt3 = new SimpleDateFormat("yyyy年mm月dd日 hh时mm分");
        Date date3 = null;
        try {
            date3 = myFmt3.parse(time3);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date3);

        //SimpleDataFormat转换格式是线程不安全的,所以也可以采用JDK1.8后的新特性DateTimeFormatter类来进行转换
        //利用DateTimeFormatter与LocalDateTime进行日期时间转换  Text -> Date
        String date4 = "21/10/19 19:52:20";
        DateTimeFormatter dtf4 = DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(date4, dtf4);
        System.out.println(localDateTime);

        //利用DateTimeFormatter与LocalDateTime进行日期时间转换  Date -> Text
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        System.out.println(format);


    }
}

运行结果:

21/10/19 20:12:13
Tue Oct 19 19:47:00 CST 2021
Fri Jan 19 23:10:00 CST 2018
2021-10-19T19:52:20
2021-10-19 20:12:13

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值