时间戳
获取时间戳的方式
方式一(推荐)
Long ts = Instant . now ( ) . toEpochMilli ( )
方式二
Long ts = System . currentTimeMillis ( )
时间戳转换
时间戳转为LocalDateTime
public LocalDateTime transfer ( Long timestamp) {
Instant instant = Instant . ofEpochMilli ( timestamp) ;
return LocalDateTime . ofInstant ( instant, ZoneId . systemDefault ( ) ) ;
}
LocalDateTime转为时间戳
public Long transfer ( LocalDateTime time) {
Instant instant = time. atZone ( ZoneId . systemDefault ( ) ) . toInstant ( ) ;
return instant. toEpochMilli ( ) ;
}
时间戳的应用
通过时间戳计算代码执行时间
计算时间戳的差值
long start = Instant . now ( ) . toEpochMilli ( ) ;
long end = Instant . now ( ) . toEpochMilli ( ) ;
System . out. println ( "共耗时:" + ( ( end - start) / 1000 ) + "s" ) ;
将时间戳的差转为指定格式
Long time1 = Instant . now ( ) . toEpochMilli ( ) ,
time2 = Instant . now ( ) . plusSeconds ( 3000 ) . toEpochMilli ( ) ;
Duration duration = Duration . ofMillis ( time2 - time1) ;
long hours = duration. toHours ( ) ;
long minutes = duration. minusDays ( days) . minusHours ( hours) . toMinutes ( ) ;
long seconds = duration. minusDays ( days) . minusHours ( hours) . minusMinutes ( minutes) . getSeconds ( ) ;
System . out. println ( hours + "小时" + minutes + "分钟" + seconds + "秒" ) ;
时区相关
LocalDateTime localDateTime = LocalDateTime . of ( 2023 , 10 , 1 , 15 , 30 ) ;
ZoneId zoneId = ZoneId . of ( "Asia/Shanghai" ) ;
ZonedDateTime zonedDateTime = localDateTime. atZone ( zoneId) ;
DateTimeFormatter formatter = DateTimeFormatter . ofPattern ( "yyyy-MM-dd HH:mm:ss" ) ;
String formattedDateTime = zonedDateTime. format ( formatter) ;
System . out. println ( formattedDateTime) ;