public class DateUtils {
/**
* 日期格式化模板
*/
private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* ThreadLocal保证SimpleDateFormat线程安全
*/
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
// 格式化模板线程安全
return new SimpleDateFormat(DATE_FORMAT_PATTERN);
}
};
/**
* 获取当前时间的毫秒数
*
* @return 当前时间的毫秒数
*/
public static long getCurrentTimeMillis() {
return System.currentTimeMillis();
}
/**
* 获取指定时间的毫秒数
*
* @param date 时间
* @return 指定时间的毫秒数
*/
public static long getTimeInMillis(Date date) {
return date.getTime();
}
/**
* 获取当前时间的指定格式字符串
*
* @param format 格式化模板
* @return 当前时间指定格式的字符串
*/
public static String format(String format) {
return DATE_FORMAT.get().format(new Date(getCurrentTimeMillis()));
}
/**
* 按照指定格式将指定时间转换为字符串
*
* @param date 时间
* @param format 格式化模板
* @return 指定时间的指定格式字符串
*/
public static String format(Date date, String format) {
return DATE_FORMAT.get().format(date);
}
/**
* 将指定时间字符串按照指定格式转换为Date对象
*
* @param dateStr 时间字符串
* @param format 格式化模板
* @return 指定格式字符串对应的Date对象
* @throws Exception 转换异常信息
*/
public static Date parse(String dateStr, String format) throws Exception {
return DATE_FORMAT.get().parse(dateStr);
}
}
高并发环境下的日期处理
最新推荐文章于 2024-09-10 10:21:38 发布