java老鸟教你如何高效优雅的进行时间格式化

您所在的位置:网站首页 java改变日期格式 java老鸟教你如何高效优雅的进行时间格式化

java老鸟教你如何高效优雅的进行时间格式化

2024-06-30 04:38| 来源: 网络整理| 查看: 265

前言

在日常项目开发过程中,相信大家一定都经常遇到时间格式化的场景。很多人可能都感觉非常简单,但是你的时间格式化方法真的优雅高效吗?

一、常见时间格式化方式 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); } 二、分析 方式一:新人菜鸟实现

很多新人喜欢采用SimpleDateFormat进行时间格式化,这也是java8之前,jdk默认提供的时间格式化实现方式,它最大的问题是非线程安全的。

原因: 在多线程环境下,当多个线程同时使用相同的SimpleDateFormat对象(如static修饰)的话,如调用format方法时,多个线程会同时调用calender.setTime方法,导致time被别的线程修改,因此线程是不安全的。

/** * SimpleDateFormat线程安全测试 */ public class SimpleDateFormatTest { private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue(1000), new MyThreadFactory("SimpleDateFormatTest")); public void test() { while (true) { poolExecutor.execute(new Runnable() { @Override public void run() { String dateString = simpleDateFormat.format(new Date()); try { Date parseDate = simpleDateFormat.parse(dateString); String dateString2 = simpleDateFormat.format(parseDate); System.out.println(dateString.equals(dateString2)); } catch (ParseException e) { e.printStackTrace(); } } }); } }

输出:

true false true true false

出现了false,说明线程不安全

format方法源码分析:

protected Calendar calendar; // Called from Format after creating a FieldDelegate private StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) { // Convert input date to time field list calendar.setTime(date); boolean useDateFormatSymbols = useDateFormatSymbols(); for (int i = 0; i >> 8; int count = compiledPattern[i++] & 0xff; if (count == 255) { count = compiledPattern[i++]


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3