Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One of my colleagues eventually came up with the right answer. The problem with incrementally adding a month to a Calendar is that you go from Jan 31 to Feb 28 to Mar 28, instead of Mar 31. This adds inaccuracy. The solution is to add 1 month, 2 months, 3 months and so on to the original start date. Then you go from Jan 31 to feb 28 to Mar 31. Anyway, here is his solution, slightly altered by me.</p> <pre><code>public class TimeSpan { public int months; public int days; public int hours; public int minutes; } class DateCalculator { public static TimeSpan difference(Date later, Date earlier) { TimeSpan v = new TimeSpan(); /* Add months until we go past the target, then go back one. */ while (calculateOffset(earlier, v).compareTo(later) &lt;= 0) { v.months++; } v.months--; /* Add days until we go past the target, then go back one. */ while (calculateOffset(earlier, v).compareTo(later) &lt;= 0) { v.days++; } v.days--; /* Add hours until we go past the target, then go back one. */ while (calculateOffset(earlier, v).compareTo(later) &lt;= 0) { v.hours++; } v.hours--; while (calculateOffset(earlier, v).compareTo(later) &lt;= 0) { v.minutes++; } v.minutes--; return v; } private static Date calculateOffset(Date start, TimeSpan offset) { Calendar c = new GregorianCalendar(); c.setTime(start); c.add(Calendar.MONTH, offset.months); c.add(Calendar.DAY_OF_YEAR, offset.days); c.add(Calendar.HOUR, offset.hours); c.add(Calendar.MINUTE, offset.minutes); return c.getTime(); } public static void main(String[] args) { try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); df.setTimeZone(TimeZone.getTimeZone("EST")); Date from = df.parse("2013-01-31 00:00"); Date to = df.parse("2014-01-31 10:20"); TimeSpan ts = difference(to, from); System.out.printf("Months:%02d Days:%02d Hrs:%02d Mins:%02d\n", ts.months, ts.days, ts.hours, ts.minutes); } catch (Exception e) { e.printStackTrace(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload