-2

I have four dates and I want to calculate the days difference between dates. My program is as below.

    Date d1 = new Date("11/28/14 23:59:58");
    Date d2 = new Date("11/29/14 00:00:02");
    Date d3 = new Date("11/29/14 23:59:58");
    Date d4 = new Date("11/30/14 00:00:02");

    final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;

    int diff1 = (int) ((d2.getTime()- d1.getTime())/DAY_IN_MILLIS);
    int diff2 = (int) ((d3.getTime()- d1.getTime())/DAY_IN_MILLIS);
    int diff3 = (int) ((d4.getTime()- d1.getTime())/DAY_IN_MILLIS);



    System.out.println(diff1);
    System.out.println(diff2);
    System.out.println(diff3);

I want diff1=1, diff2=1 & diff3=2.

But my output is diff1=0, diff2=1, diff2=1.

3 Answers3

2

You can solve this using the modern Java 8 time API:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yy HH:mm:ss");
LocalDate d1 = LocalDate.parse("11/28/14 23:59:58", formatter);
LocalDate d2 = LocalDate.parse("11/29/14 00:00:02", formatter);
LocalDate d3 = LocalDate.parse("11/29/14 23:59:58", formatter);
LocalDate d4 = LocalDate.parse("11/30/14 00:00:02", formatter);
int diff1 = d1.until(d2).getDays();
int diff2 = d1.until(d3).getDays();
int diff3 = d1.until(d4).getDays();
System.out.println(diff1);
System.out.println(diff2);
System.out.println(diff3);
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
1

There's a 4 second different between d2 and d1, so 0 days makes sense for diff1.

Between d3 and d1 there 1 day exactly, which is what you got in diff2.

Between d4 and d1 there's a little over 1 day (1 day and 4 seconds), so 1 makes sense in diff3 when using int division.

To make it clearer, here are the results when using floating point division :

4.6296296296296294E-5
1.0
1.0000462962962964
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks Eran.... but as per my requirement is that whenever there is date change, it should give me diffrence as 1. Even if diffrence is 1 second. so please guide me how to do this. – ChandraBhan Jun 26 '15 at 09:19
  • @ChandraBhan What if both dates have the same day (for example d3 and d2). Do you expect to get 0 or 1? – Eran Jun 26 '15 at 09:23
  • if both dates are same then I would expect 0. – ChandraBhan Jun 26 '15 at 09:56
1

it is only 4 sec diference between d2 and d1. Hence, the num of full days between them is 0 and not 1 as you would expect because the diff is treated as the diff between 2 timestamps. I strongly recommend you to use Joda Time, which is a easier API than Date. You can then use:

int days = Days.daysBetween(d2, d1).getDays();
aviad
  • 8,229
  • 9
  • 50
  • 98
  • Thanks ! But as per my requirement, Even if there is difference of 1 second between 2 dates, it should return 1. Its like d1 is monday and d2 is tuesday....so difference should return 1. – ChandraBhan Jun 26 '15 at 09:58
  • then work with the timestamps :) good luck with your requirements – aviad Jun 26 '15 at 12:02