1、LocalDateTime获取毫秒数
//获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
2、Date与LocalDateTime互转
//将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
public static LocalDateTime dateConvertToLocalDateTime(Date date) {
return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
}
//将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
}
3、将LocalDateTime转为自定义的时间格式的字符串
// DateTimeFormatter.ISO_DATE相当于DateTimeFormatter.ofPattern("yyyy-MM-dd")
// 还有DateTimeFormatter.ISO_DATE_TIME
// DateTimeFormatter.ISO_TIME
String format = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE);
public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDateTime.format(formatter);
}
4、将某时间字符串转为自定义时间格式的LocalDateTime
// DateTimeFormatter.ISO_DATE相当于DateTimeFormatter.ofPattern("yyyy-MM-dd")
// 还有DateTimeFormatter.ISO_DATE_TIME
// DateTimeFormatter.ISO_TIME
String format = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE);
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
5、将long类型的timestamp转为LocalDateTime
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
6、将LocalDateTime转为long类型的timestamp
public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return instant.toEpochMilli();
}