LocalDate,LocalDateTime,Date及时间戳的转换

1.时间戳转LocalDateTime,时间戳如果是字符串则先转为long
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(System.currentTimeMillis()/1000, 0, ZoneOffset.ofHours(8));
2.日期字符串转LocalDate
LocalDate parse = LocalDate.parse(“2020-05-13”);
3.LocalDateTime转LocalDate
LocalDate localDate = LocalDateTime.now().toLocalDate();

4.Date转LocalDate
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();
或使用系统默认时区
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
5.时间戳转Date
Date date = new Date(System.currentTimeMillis());

date.setTime(System.currentTimeMillis());
6.Date转LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
7.LocalDateTime转Date
Date date1 = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
8.LocalDate转Date
ZonedDateTime zonedDateTime = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
Date date = Date.from(zonedDateTime.toInstant());

9.获取前一天0和24点时间戳
秒:
long startTime = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN).toEpochSecond(ZoneOffset.of("+8"));
long endTime = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX).toEpochSecond(ZoneOffset.of("+8"));
毫秒:
long startTimeMill = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli();
long endTimeMill = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX).toInstant(ZoneOffset.of("+8")).toEpochMilli();
10.时间格式
//时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
System.out.println("formate: "+ now.format(formatter));
11.获取时间差
startTime和endTime为LocalDateTime,获取相差多少天如下:
long days = startTime.until(endTime,ChronoUnit.DAYS);

参考:
参考博主

你可能感兴趣的:(java,java)