java 时间天数差_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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值