public static void main(String[] args) {
/*
* truncatedTo方法介绍:
* 返回LocalDateTime的副本,其中时间被截断。
*
* 截断返回原始日期-时间的副本,其中小于指定单元的字段设置为零。
* 例如,使用minutes单元进行截断将把秒分和纳秒字段设置为零。
*
* 单位的持续时间必须是一个标准日的长度,没有余数。
* 这包括ChronoUnit和DAYS上提供的所有时间单位。
* 其他单元抛出异常。
*/
//时间戳
long ts = 1615797812000L; // 2021-03-15 16:43:32
//时间戳转LocalDateTime
LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(ts), ZoneOffset.ofHours(8));
//当时分0秒
long l = time.truncatedTo(ChronoUnit.MINUTES).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
System.out.println(l); // 1615797780000 2021-03-15 16:43:00
//当时0分0秒
l = time.truncatedTo(ChronoUnit.HOURS).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
System.out.println(l); // 1615795200000 2021-03-15 16:00:00
//当天0点
l = time.truncatedTo(ChronoUnit.DAYS).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
System.out.println(l); // 1615737600000 2021-03-15 00:00:00
//当月0点
l = time.truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
System.out.println(l); // 1614528000000 2021-03-01 00:00:00
//当年0点
l = time.truncatedTo(ChronoUnit.DAYS).withDayOfYear(1).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
System.out.println(l); // 1609430400000 2021-01-01 00:00:00
}
时间戳转0点0分0秒(truncatedTo 当天当月当年)
最新推荐文章于 2024-03-06 11:52:16 发布