DateUtil.java 2.11 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
package com.lyms.talkonlineweb.util;

import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* @ProjectName: talkonline
* @Package: com.lyms.talkonlineweb.util
* @ClassName: DateUtil
* @Author: lqy
* @Description: 时间格式类
* @Date: 2021-09-07 17:53
* @Version:
*/
public class DateUtil {
/**
* 缓存时间格式化
*/
private static ConcurrentHashMap<String, DateFormat> dateFormatCache = new ConcurrentHashMap<String, DateFormat>();
private static Lock lock = new ReentrantLock();

public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
/**
* 私有构造方法,禁止对该类进行实例化
*/
private DateUtil() {
}

public static String getYyyyMmDdHhMmSs(Date datetime) {
return getDateTime(datetime, YYYY_MM_DD_HH_MM_SS);
}

public static String getDateTime(Date date, String pattern) {
if (date == null) {
return "";
}

DateFormat format = getDateFormat(pattern);
lock.lock();
try {
return format.format(date);
} finally {
lock.unlock();
}
}

public static DateFormat getDateFormat(String pattern) {
if (StringUtil.isEmpty(pattern)) {
pattern = YYYY_MM_DD;
}

if (dateFormatCache.get(pattern) != null) {
return dateFormatCache.get(pattern);
}
lock.lock();
try {
DateFormat format = new SimpleDateFormat(pattern);
dateFormatCache.put(pattern, format);
return format;
} catch (Exception e) {
} finally {
lock.unlock();
}
return null;
}

public static String getSeqString() {
SimpleDateFormat fm = new SimpleDateFormat("yyMMddHHmmss");
return fm.format(new Date());
}

}