Wrong time calculated in minutes from two Date objects to calculate duration

Tags: , , , ,



I am trying to calculate the duration between two date objects in minutes.

I have found some inspiration during my research from this stackoverflow question. In generally this seems to work correct, but I’m experiencing an interesting behaviour for one testcase.

When I run the below attached sourcecode (You can simply copy past it), it returns me 66 minutes instead of (the correct result) 6 and I currently don’t understand why. Perhaps I’m overseeing something at the moment, can you tell me what it is?

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Test {

    private SimpleDateFormat parserSDF = new SimpleDateFormat("MM/dd/yy HH:mm",
            Locale.ENGLISH);

    public static void main(String[] args) {
        Test test = new Test();
        Date begin = test.createDateFromString("10/25/09 1:54");
        Date end = test.createDateFromString("10/25/09 2:00");

        int duration = test.minutesDiff(begin, end);
        //result is 66
        System.out.println(duration);
    }

    public int minutesDiff(Date earlierDate, Date laterDate) {
        if (earlierDate == null || laterDate == null)
            return 0;

        return (int) ((laterDate.getTime() / 60000) - (earlierDate.getTime() / 60000));
    }

    public Date createDateFromString(String dateString) {
        Date date = null;
        try {
            date = parserSDF.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

I know btw that there exists this Joda library which does way better in computing this stuff, but if possible, I would like to stay without an external library.

Thanks for every thought you’re sharing with me.

EDIT: Aaaah, might it be possible that this is because clock change? Clock change was at the 25th of October 2009 and the time got set back from 3am to 2am. This could mean that this result is correct

Answer

Depending on your locale, it looks like it was the ending of Daylight Savings Time a.k.a Summer Time. Here’s the 2009 table; October 25, 2009 was the ending date for many locales. It would explain why 66 showed up instead of 6; there were 60 extra minutes.



Source: stackoverflow