ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-04-22 21:33:10  阅读:61  来源: 互联网

标签:Java long zoneId static LocalDateTime Date timeMillis


一、时间戳与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();
}

标签:Java,long,zoneId,static,LocalDateTime,Date,timeMillis
来源: https://www.cnblogs.com/convict/p/16180586.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有