package com.dsh.utils;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.util.Assert;
|
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.time.Duration;
|
import java.time.LocalDateTime;
|
import java.time.format.DateTimeFormatter;
|
import java.util.Date;
|
|
/**
|
* @author: lihong .
|
* @email: lihongvst@foxmail.com .
|
* @createTime: 2019/6/26 18:02 .
|
* @describe: 时间工具类.
|
**/
|
@Slf4j
|
public final class DateUtils {
|
public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
|
public static final String yy_LINK_MM = "yyMM";
|
public static final String yyyy_MM_dd = "yyyy-MM-dd";
|
|
|
/**
|
* 格式化时间
|
*
|
* @param localDateTime
|
* @param parse
|
* @return
|
*/
|
public static String parseDate(LocalDateTime localDateTime, String parse) {
|
return localDateTime.format(DateTimeFormatter.ofPattern(parse));
|
}
|
|
/**
|
* 时间转时间
|
*
|
* @param date
|
* @param parse
|
* @return
|
*/
|
public static Date dateToDate(Date date, String parse) {
|
SimpleDateFormat sdf = new SimpleDateFormat(parse);
|
try {
|
return sdf.parse(sdf.format(date));
|
} catch (ParseException e) {
|
e.printStackTrace();
|
log.error("格式化时间异常, date:{}, parse:{}", date, parse);
|
}
|
return null;
|
}
|
|
|
/**
|
* 差值计算
|
*
|
* @param startTime
|
* @param endTime
|
* @return 毫秒
|
*/
|
public static long diff(LocalDateTime startTime, LocalDateTime endTime) {
|
Assert.notNull(startTime, "开始时间不能为空.");
|
Assert.notNull(endTime, "结束时间不能为空");
|
Duration duration = Duration.between(startTime, endTime);
|
return duration.toMillis();
|
}
|
|
/**
|
* 根据给出的Date值和格式串采用操作系统的默认所在的国家风格来格式化时间,并返回相应的字符串
|
*
|
* @param date
|
* @param formatStr
|
* @return 如果为null,返回字符串""
|
*/
|
public static String formatDateTimeToString(Date date, String formatStr) {
|
String reStr = "";
|
if (date == null || formatStr == null || formatStr.trim().length() < 1) {
|
return reStr;
|
}
|
SimpleDateFormat sdf = new SimpleDateFormat();
|
sdf.applyPattern(formatStr);
|
reStr = sdf.format(date);
|
return reStr;
|
}
|
|
}
|