欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java计算两个时间的天数差与月数差 LocalDateTime,如何计算日期差的天数

来源: javaer 分享于  点击 12807 次 点评:272

Java计算两个时间的天数差与月数差 LocalDateTime,如何计算日期差的天数


 /**
  * 计算两个时间点的天数差
  * @param dt1 第一个时间点
  * @param dt2 第二个时间点
  * @return int,即要计算的天数差
  */
 public static int dateDiff(LocalDateTime dt1,LocalDateTime dt2){
  //获取第一个时间点的时间戳对应的秒数
  long t1 = dt1.toEpochSecond(ZoneOffset.ofHours(0));
  //获取第一个时间点在是1970年1月1日后的第几天
  long day1 = t1 /(60*60*24);
  //获取第二个时间点的时间戳对应的秒数
  long t2 = dt2.toEpochSecond(ZoneOffset.ofHours(0));
  //获取第二个时间点在是1970年1月1日后的第几天
  long day2 = t2/(60*60*24);
  //返回两个时间点的天数差
  return (int)(day2 - day1);
 }
 @Test
 public void testDay(){
  LocalDateTime of1 = LocalDateTime.of(2018, 9, 25, 1, 1);//2018-9-25 01:01
  LocalDateTime of2 = LocalDateTime.of(2019, 9, 25, 23, 16); //2019-9-25 23:16
  System.out.println(dateDiff(of1,of2));//365
 }

 /**
  * 获取两个时间点的月份差
  * @param dt1 第一个时间点
  * @param dt2 第二个时间点
  * @return int,即需求的月数差
  */
 public static int monthDiff(LocalDateTime dt1,LocalDateTime dt2){
  //获取第一个时间点的月份
  int month1 = dt1.getMonthValue();
  //获取第一个时间点的年份
  int year1 = dt1.getYear();
  //获取第一个时间点的月份
  int month2 = dt2.getMonthValue();
  //获取第一个时间点的年份
  int year2 = dt2.getYear();
  //返回两个时间点的月数差
  return (year2 - year1) *12 + (month2 - month1);
 }
  @Test
 public void testMonth(){
  LocalDateTime of1 = LocalDateTime.of(2018, 9, 25, 1, 1);//2018-9-25 01:01
  LocalDateTime of2 = LocalDateTime.of(2019, 9, 25, 23, 16); //2019-9-25 23:16
  System.out.println(monthDiff(of1,of2));//12
 }

 

相关文章

    暂无相关文章
相关栏目:

用户点评