Java版的datediff

  MSSQL中提供了个datediff函数用来对两个时间进行减法操作,但在Java中却没有,如果我们想知道两个日期间相隔了多少天,或是相隔了多少个小时则要手工计算。下面代码模仿MSSQL的datediff函数提供了使用不同时间间隔来计算两个时间相差的时间间隔的数目,比如timeInterval为day则返回相差的天数,为month则返回相差的月数。总共支持year,quarter,month,week,day,hour,minute,second这几种时间间隔,date1和date2为要计算的两个时间,结果为date1减去date2后的值。


 /**
  * 按指定日期单位计算两个日期间的间隔
  *
  * @param timeInterval
  * @param date1
  * @param date2
  * @return
  */
 public static long dateDiff(String timeInterval, Date date1, Date date2) {
  if (timeInterval.equals("year")) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date1);
   int time = calendar.get(Calendar.YEAR);
   calendar.setTime(date2);
   return time - calendar.get(Calendar.YEAR);
  }

  if (timeInterval.equals("quarter")) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date1);
   int time = calendar.get(Calendar.YEAR) * 4;
   calendar.setTime(date2);
   time -= calendar.get(Calendar.YEAR) * 4;
   calendar.setTime(date1);
   time += calendar.get(Calendar.MONTH) / 4;
   calendar.setTime(date2);
   return time - calendar.get(Calendar.MONTH) / 4;
  }

  if (timeInterval.equals("month")) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date1);
   int time = calendar.get(Calendar.YEAR) * 12;
   calendar.setTime(date2);
   time -= calendar.get(Calendar.YEAR) * 12;
   calendar.setTime(date1);
   time += calendar.get(Calendar.MONTH);
   calendar.setTime(date2);
   return time - calendar.get(Calendar.MONTH);
  }

  if (timeInterval.equals("week")) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date1);
   int time = calendar.get(Calendar.YEAR) * 52;
   calendar.setTime(date2);
   time -= calendar.get(Calendar.YEAR) * 52;
   calendar.setTime(date1);
   time += calendar.get(Calendar.WEEK_OF_YEAR);
   calendar.setTime(date2);
   return time - calendar.get(Calendar.WEEK_OF_YEAR);
  }

  if (timeInterval.equals("day")) {
   long time = date1.getTime() / 1000 / 60 / 60 / 24;
   return time - date2.getTime() / 1000 / 60 / 60 / 24;
  }

  if (timeInterval.equals("hour")) {
   long time = date1.getTime() / 1000 / 60 / 60;
   return time - date2.getTime() / 1000 / 60 / 60;
  }

  if (timeInterval.equals("minute")) {
   long time = date1.getTime() / 1000 / 60;
   return time - date2.getTime() / 1000 / 60;
  }

  if (timeInterval.equals("second")) {
   long time = date1.getTime() / 1000;
   return time - date2.getTime() / 1000;
  }

  return date1.getTime() - date2.getTime();
 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值