一:计算到天数(12-26——12-31相差天数毫秒数)
@Test
void test33() {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前月的最后一天
LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());
// 计算秒数
long secondsUntilEndOfMonth = currentDate.until(lastDayOfMonth, ChronoUnit.DAYS) * 24 * 60 * 60;
System.out.println("当前时间到当前月最后一天的秒数为:" + secondsUntilEndOfMonth + " 秒");
}
效果:
二:计算到秒数(12月31日15时48分21秒——12月31日23时59分59秒相差天数毫秒数)
@Test
void test34(){
// 定义当前时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//当前时间
String currentDate = sdf.format(new Date());
//获取当前月最后一天
LocalDate lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
//定义当前月最后一天时间格式
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String endDate = dtf.format(lastDayOfMonth) + " 23:59:59";
// 将字符串转换为LocalDateTime对象
LocalDateTime currentDateTime = LocalDateTime.parse(currentDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime endDateTime = LocalDateTime.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 计算两个时间的秒差异
long secondDiff = ChronoUnit.SECONDS.between(currentDateTime, endDateTime);
System.out.println("两个时间相差 " + secondDiff + " 秒。");
}
效果: