Java中时间戳与Date/LocalDateTime的相互转换

一、时间戳与Date相互转换#

1. 时间戳转Date#

public static void timestamp2Date() {
	long timeMillis = System.currentTimeMillis();
	Date date = new Date(timeMillis);
}

2. Date转时间戳#

public static void date2Timestamp() {
	Date date = new Date();
	long timeMillis = date.getTime();
}

二、时间戳与LocalDateTime相互转换#

1. 时间戳转LocalDateTime#

public static void timestamp2LocalDateTime() {
	long timeMillis = System.currentTimeMillis();
	ZoneId zoneId = ZoneId.systemDefault();
	LocalDateTime localDateTime = Instant.ofEpochMilli(timeMillis).atZone(zoneId).toLocalDateTime();
}

2. LocalDateTime转时间戳#

public static void localDateTime2Timestamp() {
	ZoneId zoneId = ZoneId.systemDefault();
	LocalDateTime now = LocalDateTime.now();
	long epochMilli = now.atZone(zoneId).toInstant().toEpochMilli();
}

posted @   Convict  阅读(10469)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2021-04-22 Windows安装MySQL5.7解压版
点击右上角即可分享
微信分享提示
主题色彩