package com.example.util;
import org.apache.commons.lang.StringUtils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
/**
* @author :zhaoyu
* @date :Created in 2019/3/7 11:28
*/
public class DateTimeUtils {
public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
public static final String HHMMSS = "HH:mm:ss";
public static final String YYYYMMDD = "yyyy-MM-dd";
/**
* 根据local时间获取时间戳
*
* @param localDateTime
* @return
*/
public static long getTimeStamp(LocalDateTime localDateTime) {
if (Objects.isNull(localDateTime)) {
throw new IllegalArgumentException("参数不能为空");
}
return localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
}
public static LocalDateTime getLocalDateTime(long timestamp) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
}
public static LocalDateTime getLocalDateTime(Date date) {
if (Objects.isNull(date)) {
throw new IllegalArgumentException("参数不能为空");
}
return getLocalDateTime(date.getTime());
}
public static LocalDateTime getLocalDateTime(String localDateTime, String pattern) {
if (StringUtils.isBlank(localDateTime)) {
throw new IllegalArgumentException("参数不能为空");
}
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.parse(localDateTime, dateTimeFormatter);
}
public static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return localDateTime.format(dateTimeFormatter);
}
public static String formatLocalDateTime(LocalDateTime localDateTime) {
return formatLocalDateTime(localDateTime, YYYYMMDDHHMMSS);
}
public static LocalDateTime getLocalDateTime(String localDateTime) {
return getLocalDateTime(localDateTime, YYYYMMDDHHMMSS);
}
}