DateUtils.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package cn.com.taiji.utils;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. /**
  8. * @author xhl
  9. * @date 2022/11/20
  10. */
  11. public class DateUtils {
  12. /**
  13. * 常规日期时间格式,24小时制yyyy-MM-dd HH:mm:ss
  14. */
  15. public static final String NORMAL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
  16. /**
  17. * 常规日期,yyyy-MM-dd
  18. **/
  19. public static final String NORMAL_DATE_FORMAT = "yyyy-MM-dd";
  20. /**
  21. * 锁对象
  22. */
  23. private static final Object LOCK_OBJ = new Object();
  24. /**
  25. * 存放不同的日期模板格式的SimpleDateFormat的Map
  26. */
  27. private static Map<String, ThreadLocal<SimpleDateFormat>> threadLocalMap = new HashMap<>(8);
  28. /**
  29. * 返回一个ThreadLocal的SimpleDateFormat,每个线程只会new一次
  30. *
  31. * @param pattern
  32. * @return
  33. */
  34. private static SimpleDateFormat getDateFormat(final String pattern) {
  35. ThreadLocal<SimpleDateFormat> tl = threadLocalMap.get(pattern);
  36. // 双重判断和同步,防止threadLocalMap这个单例被多次重复的SimpleDateFormat
  37. if (tl == null) {
  38. synchronized (LOCK_OBJ) {
  39. tl = threadLocalMap.get(pattern);
  40. if (tl == null) {
  41. tl = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
  42. threadLocalMap.put(pattern, tl);
  43. }
  44. }
  45. }
  46. return tl.get();
  47. }
  48. /**
  49. * 日期转字符串
  50. *
  51. * @param date
  52. * @param format
  53. * @return
  54. */
  55. public static String format(Date date, String format) {
  56. return getDateFormat(format).format(date);
  57. }
  58. /**
  59. * 字符串转日期
  60. *
  61. * @param dateStr
  62. * @param format
  63. * @return
  64. * @throws ParseException
  65. */
  66. public static Date parse(String dateStr, String format) throws ParseException {
  67. return getDateFormat(format).parse(dateStr);
  68. }
  69. }