public class DateUtils {
/**
* 默认的日期格式
*/
private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 日期格式化数组
*/
private static final DateFormat[] DATE_FORMATS = {
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S"),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd HH:mm"),
new SimpleDateFormat("yyyy-MM-dd HH"),
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy-MM")
};
private DateUtils() {
}
/**
* 将字符串转换成日期
*
* @param source 日期字符串
* @return 日期
*/
public static Date convert(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
source = source.trim();
Date date = null;
for (DateFormat dateFormat : DATE_FORMATS) {
try {
date = dateFormat.parse(source);
break;
} catch (ParseException e) {
log.error("日期转换异常:{}", source);
}
}
return date;
}
/**
* 格式化日期
*
* @param date 日期
* @param pattern 格式
* @return 格式化的日期
*/
public static String formatDate(Date date, String pattern) {
if (date == null || StringUtils.isBlank(pattern)) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
/**
* 格式化日期(yyyy-MM-dd HH:mm:ss)
*
* @param date 日期
* @return 格式化的日期
*/
public static String formatDate(Date date) {
if (date == null) {
return null;
}
return formatDate(date, DEFAULT_PATTERN);
}
/**
* 获取偏移天数日期的开始日期(2020-01-01 00:00:00)
* <p>
* 比如:getStartDate(0) 获取今日开始时间,getStartDate(1) 获取昨日开始时间,getStartDate(-1) 获取明日开始时间
* </p>
*
* @param offset 偏移(0代表当天)
* @return 偏移天数的开始时间
*/
public static Date getDayStartDate(int offset) {
LocalDateTime startLocalDateTime = LocalDateTime.now()
.minusDays(offset)
.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
return Date.from(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 获取偏移天数的开始日期字符串
*
* @param offset 偏移(0代表当天)
* @return 偏移天数的开始时间字符串
*/
public static String getDayStartDateStr(int offset) {
return formatDate(getDayStartDate(offset));
}
/**
* 获取偏移天数日期的结束日期(2020-01-01 23:59:59)
* <p>
* 比如:getEndDate(0) 获取今日结束时间,getEndDate(1) 获取昨日结束时间,getEndDate(-1) 获取明日结束时间
* </p>
*
* @param offset 偏移(0代表当天)
* @return 偏移天数的结束时间
*/
public static Date getDayEndDate(int offset) {
LocalDateTime startLocalDateTime = LocalDateTime.now()
.minusDays(offset)
.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999999);
return Date.from(startLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 获取偏移天数的结束日期字符串
*
* @param offset 偏移(0代表当天)
* @return 偏移天数的结束时间字符串
*/
public static String getDayEndDateStr(int offset) {
return formatDate(getDayEndDate(offset));
}
/**
* 获取当前年份
*
* @return 当前年份
*/
public static int getCurrentYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
/**
* 获取当前月份
*
* @return 当年月份
*/
public static int getCurrentMonth() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
}