LocalDateTime与String、Date的互转
废话不说了,直接上代码,喜欢自取;可以封装成util类~~
1、得到当前的localDateTime
public static LocalDateTime getLocalDateTimeNow() {
return LocalDateTime.now();
}
2、String 按照一定的格式转换成LocalDateTime
public static LocalDateTime localDateTimeParse(String time, String pattern) {
return LocalDateTime.parse(time, DateTimeFormatter.ofPattern(pattern));
}
3、localDateTime 按照一定的格式转换成String
public static String localDateTimeFormat(LocalDateTime localDateTime, String pattern) {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
4、Date 转换为LocalDateTime,默认时区为东8区
public static LocalDateTime dateConvertToLocalDateTime(Date date) {
return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
}
5、LocalDateTime 转换为 Date,默认时区为东8区
public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
}
6、计算两个LocalDateTime 之间的毫秒数
public static Long minusToMillsLocalDateTime(LocalDateTime time1, LocalDateTime time2) {
return Duration.between(time1, time2).toMillis();
}
7、LocalDateTime获取毫秒数
获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();