失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > LocalDateTime获取时间戳 LocalDateTime与String互转 Date与LocalDateTime互转(Java8 特性)

LocalDateTime获取时间戳 LocalDateTime与String互转 Date与LocalDateTime互转(Java8 特性)

时间:2018-12-10 13:47:50

相关推荐

LocalDateTime获取时间戳 LocalDateTime与String互转 Date与LocalDateTime互转(Java8 特性)

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();

如果觉得《LocalDateTime获取时间戳 LocalDateTime与String互转 Date与LocalDateTime互转(Java8 特性)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。