Finding days difference in java

后端 未结 5 476
有刺的猬
有刺的猬 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:16

    Using float, I see the problem. Using timestamp doesn't seem like a good approach to finding the days difference between 2 dates.

    11 to 11 = 0.0
    11 to 12 = 1.0
    11 to 13 = 2.0
    11 to 14 = 3.0
    11 to 15 = 3.9583333
    11 to 16 = 4.9583335
    11 to 17 = 5.9583335
    11 to 18 = 6.9583335
    11 to 19 = 7.9583335

    Going forward, I find the most conclusive way to determine the date difference as

    Calendar cre_calendar = new GregorianCalendar((2013), (1), 11);
            Calendar exp_calendar = new GregorianCalendar((2013), (1), 19);
            Calendar maxDays = new GregorianCalendar(((2013)), (12), 31);
    
            if (exp_calendar.get(Calendar.DAY_OF_YEAR) < cre_calendar
                    .get(Calendar.DAY_OF_YEAR)) {
                System.out
                        .println((exp_calendar.get(Calendar.DAY_OF_YEAR) + maxDays
                                .get(Calendar.DAY_OF_YEAR))
                                - cre_calendar.get(Calendar.DAY_OF_YEAR));
            } else {
                System.out.println((exp_calendar.get(Calendar.DAY_OF_YEAR))
                        - cre_calendar.get(Calendar.DAY_OF_YEAR));
            }
    

提交回复
热议问题