计算月份:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(“yyyy/MM/dd”);
LocalDate startDate = LocalDate.parse(“2017/03/24”, fmt);
LocalDate endDate = LocalDate.parse(“2022/01/22”, fmt);
Period p = Period.between(startDate, endDate);
System.out.printf(“目标日期距离今天的时间差:%d 年 %d 个月 %d 天\n”, p.getYears(), p.getMonths(), p.getDays());
System.out.printf(“目标日期距离今天的时间差 %d 个月\n”, p.getYears()*12+ p.getMonths());
计算天数:
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd”, Locale.ENGLISH);
Date startDate = sdf.parse(“2019/07/24”);
Date endDate = sdf.parse(“2019/07/30”);
long diffInMillis = Math.abs(startDate .getTime() - endDate .getTime());
long diff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
System.out.printf(“目标日期距离今天的时间差: %d 天\n”, diff );
总结
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date startDate = sdf.parse("2017/03/24");
Date endDate = sdf.parse("2022/01/22");
LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period p = Period.between(startLocalDate, endLocalDate);
System.out.printf("目标日期距离今天的时间差:%d 年 %d 个月 %d 天\n", p.getYears(), p.getMonths(), p.getDays());
System.out.printf("目标日期距离今天的时间差 %d 个月\n", p.getYears()*12+ p.getMonths());
long diffInMillis = Math.abs(startDate.getTime() - endDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
System.out.printf("目标日期距离今天的时间差: %d 天\n", diff );


1427

被折叠的 条评论
为什么被折叠?



