JAVA计算两个日期相差多少天

妖狐艹你老母 2023-01-01 03:41 345阅读 0赞

前言

有时候我们在JAVA中会比较两个日期相差多少天,这里有几个实现方法供大家参考,偶尔会用到,也当做自己收藏。btw,同时也要鄙视一下我的好基友从百度搜到的一个答案的作者,写了毒代码,计算个日期而已,竟然要遍历两个日期的time。

解决方案

有使用Calendar的,也有使用Date的,都ok。但是基本都是去获取Time进行计算。Calendar也可以换成LocalCalendar等等的。

  1. /** * JAVA计算两个日期相差多少天(by date) * @author zhengkai.blog.csdn.net */
  2. public static int daysBetween(Date date1,Date date2){
  3. Calendar cal = Calendar.getInstance();
  4. cal.setTime(date1);
  5. long time1 = cal.getTimeInMillis();
  6. cal.setTime(date2);
  7. long time2 = cal.getTimeInMillis();
  8. long between_days=(time2-time1)/(1000*3600*24);
  9. return Integer.parseInt(String.valueOf(between_days));
  10. }
  11. /** * JAVA计算两个日期相差多少天(by Date String with format "yyyy-MM-dd") * @author zhengkai.blog.csdn.net */
  12. public static int daysBetween(String date1str,String date2str){
  13. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  14. Date date1 = format.parse(date1str);
  15. Date date2 = format.parse(date2str);
  16. int a = (int) ((date1.getTime() - date2.getTime()) / (1000*3600*24));
  17. return a;
  18. }
  19. /** * JAVA比较两个日期(使用hutool库的DateUtil) * @author zhengkai.blog.csdn.net */
  20. if(DateUtil.compare(date1,date2)>0){
  21. //如果date1>=date2
  22. }else{
  23. //如果date1<date2
  24. }

批斗

以下是 有害代码,引以为戒。真的是一天一天去遍历的…

  1. public static int getDaysForTwoDate2(Date firstDate,Date secondDdate) throws ParseException {
  2. Calendar calendar = Calendar.getInstance();
  3. calendar.setTime(firstDate);
  4. int cnt = 0;
  5. while(calendar.getTime().compareTo(secondDdate)>0){
  6. calendar.add(Calendar.DATE, 1);
  7. cnt++;
  8. }
  9. System.out.println(cnt);
  10. return cnt;
  11. }

发表评论

表情:
评论列表 (有 0 条评论,345人围观)

还没有评论,来说两句吧...

相关阅读