12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package cn.com.taiji.utils;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * @author xhl
- * @date 2022/11/20
- */
- public class DateUtils {
- /**
- * 常规日期时间格式,24小时制yyyy-MM-dd HH:mm:ss
- */
- public static final String NORMAL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
- /**
- * 常规日期,yyyy-MM-dd
- **/
- public static final String NORMAL_DATE_FORMAT = "yyyy-MM-dd";
- /**
- * 锁对象
- */
- private static final Object LOCK_OBJ = new Object();
- /**
- * 存放不同的日期模板格式的SimpleDateFormat的Map
- */
- private static Map<String, ThreadLocal<SimpleDateFormat>> threadLocalMap = new HashMap<>(8);
- /**
- * 返回一个ThreadLocal的SimpleDateFormat,每个线程只会new一次
- *
- * @param pattern
- * @return
- */
- private static SimpleDateFormat getDateFormat(final String pattern) {
- ThreadLocal<SimpleDateFormat> tl = threadLocalMap.get(pattern);
- // 双重判断和同步,防止threadLocalMap这个单例被多次重复的SimpleDateFormat
- if (tl == null) {
- synchronized (LOCK_OBJ) {
- tl = threadLocalMap.get(pattern);
- if (tl == null) {
- tl = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
- threadLocalMap.put(pattern, tl);
- }
- }
- }
- return tl.get();
- }
- /**
- * 日期转字符串
- *
- * @param date
- * @param format
- * @return
- */
- public static String format(Date date, String format) {
- return getDateFormat(format).format(date);
- }
- /**
- * 字符串转日期
- *
- * @param dateStr
- * @param format
- * @return
- * @throws ParseException
- */
- public static Date parse(String dateStr, String format) throws ParseException {
- return getDateFormat(format).parse(dateStr);
- }
- }
|