0

Problem: Getting the difference in calendar days between two dates. For an example, 6/28/1996 23:59 is one day difference from 6/29/1996 12:00.

Research: I did a bunch of research online and everyone seems to only give the difference in milliseconds, which gives you the true difference in times, but not in calendar days.

Current Solution

(int) ((new java.sql.Date(System.currentTimeMillis()).getTime()/day_conversion)) - (int) (rs.getDate("attempt_time").getTime()/day_conversion) > 0

I did an int cast to the time of the date converted to days (thereby dropping any decimals) to both the current time and recorded time and took the difference. This left me with the actual conversion in calendar days; however, I was wondering if there is just a single written method that does this for me already.

Jacob Macallan
  • 879
  • 2
  • 6
  • 25

2 Answers2

5

Since Java 8 there exists the java.time API, superseding java.util.Date and related classes and providing a very clean way of solving your problem:

LocalDateTime date1 = LocalDateTime.of(1996, 6, 28, 23, 59);
LocalDateTime date2 = LocalDateTime.of(1996, 6, 29, 12, 59);

Period difference = Period.between(date1.toLocalDate(), date2.toLocalDate());
System.out.println(difference.getDays());
Beethoven
  • 365
  • 1
  • 8
0

This is another way to compute difference between years. You can add the rest of date very easily.

        Calendar c = Calendar.getInstance();
        int y = c.get(Calendar.YEAR);
        Calendar c2 = Calendar.getInstance();
        c2.set(Calendar.YEAR, 2013);
        int com = c.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
        System.out.println(com);
Jawegiel
  • 102
  • 1
  • 12