Finding days difference in java

后端 未结 5 473
有刺的猬
有刺的猬 2021-01-15 18:53

After consulting a few forums, I ended up using the code below to find the days difference. But, I see a problem with the logic (may be it\'s my over sight?). I see that for

5条回答
  •  执念已碎
    2021-01-15 19:03

    Date(year,day, month ) constructor is deprecated. i would simply use Calendars methods to get the difference between two days:

    Calendar cal1=Calendar.getInstance();
    Calendar cal2=Calendar.getInstance();
    cal1.setTime(createdDate);
    cal2.setTime(expirationDate);
    System.out.println(cal2.get(Calendar.DAY_OF_MONTH )-cal1.get(Calendar.DAY_OF_MONTH ) );
    

    EDIT:

    Calendar cal1 = Calendar.getInstance();
    cal1.set(2013, 2, 11);
    Calendar cal2 = Calendar.getInstance();
    cal2.set(2013, 2, 11);
    for (int i = 11; i < 20; i++) {
     cal2.set(Calendar.DATE, i);
        System.out.println("11 to " + i + " = " + (cal2.get(Calendar.DAY_OF_MONTH) -cal1.get(Calendar.DAY_OF_MONTH)));
    }
    

    OUTPUT:

    11 to 11 = 0
    11 to 12 = 1
    11 to 13 = 2
    11 to 14 = 3
    11 to 15 = 4
    11 to 16 = 5
    11 to 17 = 6
    11 to 18 = 7
    11 to 19 = 8
    

提交回复
热议问题