mirror of https://gitee.com/y_project/RuoYi.git
缓存SimpleDateFormat实例的Map,原代码每次new消耗性能 修改后提升性能并保证线程安全
parent
66d828ce6d
commit
7c8278fce6
|
@ -1,15 +1,16 @@
|
|||
package com.ruoyi.common.utils;
|
||||
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.*;
|
||||
import java.util.Date;
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 时间工具类
|
||||
|
@ -33,6 +34,8 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
|
|||
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
|
||||
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
|
||||
|
||||
// 缓存SimpleDateFormat实例的Map,其中每个格式字符串对应一个ThreadLocal<SimpleDateFormat>
|
||||
private static final Map<String, ThreadLocal<SimpleDateFormat>> dateFormatMap = new HashMap<>();
|
||||
/**
|
||||
* 获取当前Date型日期
|
||||
*
|
||||
|
@ -73,11 +76,39 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
|
|||
return parseDateToStr(YYYY_MM_DD, date);
|
||||
}
|
||||
|
||||
public static final String parseDateToStr(final String format, final Date date)
|
||||
{
|
||||
return new SimpleDateFormat(format).format(date);
|
||||
|
||||
/**
|
||||
* 原代码每次new消耗性能 修改后提升性能并保证线程安全
|
||||
* 将给定日期格式化为指定格式的字符串
|
||||
* @param format 日期格式字符串,例如 "yyyy-MM-dd"
|
||||
* @param date 需要格式化的日期对象
|
||||
* @return 格式化后的日期字符串
|
||||
* @throws IllegalArgumentException 如果格式字符串或日期对象为空时抛出
|
||||
*/
|
||||
public static String parseDateToStr(final String format, final Date date) {
|
||||
if (!StringUtils.hasLength(format)) {
|
||||
throw new IllegalArgumentException("Format must not be null or empty");
|
||||
}
|
||||
if (Objects.isNull(date)) {
|
||||
throw new IllegalArgumentException("Date must not be null");
|
||||
}
|
||||
return getDateFormat(format).format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取与指定格式关联的SimpleDateFormat实例
|
||||
* 如果Map中不存在该格式的实例,则创建一个新的实例并存入Map
|
||||
* @param format 日期格式字符串
|
||||
* @return 与指定格式关联的SimpleDateFormat实例
|
||||
*/
|
||||
private static SimpleDateFormat getDateFormat(final String format) {
|
||||
return dateFormatMap
|
||||
.computeIfAbsent(format
|
||||
, k -> ThreadLocal.withInitial(() -> new SimpleDateFormat(k)))
|
||||
.get();
|
||||
}
|
||||
|
||||
|
||||
public static final Date dateTime(final String format, final String ts)
|
||||
{
|
||||
try
|
||||
|
|
Loading…
Reference in New Issue