如何优雅转换且避免线程不安全的问题

一、常见时间格式化方式

public static void main(String[] args) {
    Date now = new Date(); // 创建一个Date对象,获取当前时间
    String strDateFormat = "yyyy-MM-dd HH:mm:ss";

    //新人菜鸟实现
    SimpleDateFormat f = new SimpleDateFormat(strDateFormat);
    System.out.println("SimpleDateFormat:" + f.format(now)); // 将当前时间袼式化为指定的格式

    //java8进阶实现
    LocalDateTime localDateTime = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    String result =  localDateTime.format(DateTimeFormatter.ofPattern(strDateFormat));
    System.out.println("DateTimeFormatter:"+result);

    //common-lang3老鸟实现
    result  = DateFormatUtils.format(now,strDateFormat);
    System.out.println("DateFormatUtils:"+result);

}

 

posted @ 2022-09-24 12:15  编码小高  阅读(15)  评论(0编辑  收藏  举报