jurmeneta
jurmeneta

Reputation: 44

java difference between calendars

I'm just doing a simple difference of two timemilisseconds of two different calendar.

Example:

    Calendar ini = Calendar.getInstance();
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {e.printStackTrace();}

    Calendar end = Calendar.getInstance();
    long diff = end.getTimeInMillis()-ini.getTimeInMillis();
    System.out.println("diff "+diff);
    System.out.println("ini date "+ ini.getTime());
    System.out.println("end date "+ end.getTime());
    System.out.println("diff time format "+timeFormat.format(diff));

The time format is:

private final static String TIME_STRING_FORMAT = "hh:mm:ss.SSS";
private static SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_STRING_FORMAT);

And in the output, always appear 1 our of difference, is it problem of the SimpleDateFormat???

Output:

diff 1500
ini date Sun May 24 22:27:01 CEST 2015
end date Sun May 24 22:27:03 CEST 2015
diff time format 01:00:01.500

Thanks for your help!!

Upvotes: 0

Views: 371

Answers (2)

Kasper van den Berg
Kasper van den Berg

Reputation: 9526

The 1 hour difference is caused by your local time zone. Date(long) constructs a date a number of milli seconds after January 1st 1970 GMT. In continental Europe (during winter) 1500 milli seconds after the epoch is thus January 1st 01:00:01.500.

If you use Java 8 see the tutorial on Period and Duration. Duration is probably what you want to use.

Upvotes: 2

augray
augray

Reputation: 3161

It looks like SimpleDateFormat uses a timezone. See this related question. So when you give it the time 1500 milliseconds, it thinks you're giving it the time since the beginning of epoch time in the GMT time. Then it translates this to your timezone, giving you some hours of offset. You probably want to set the timezone on your timeFormat to GMT. Try this:

    Calendar ini = Calendar.getInstance();
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {e.printStackTrace();}

    Calendar end = Calendar.getInstance();
    long diff = end.getTimeInMillis()-ini.getTimeInMillis();
    System.out.println("diff "+diff);
    System.out.println("ini date "+ ini.getTime());
    System.out.println("end date "+ end.getTime());
    Date date = new Date(diff);
    System.out.println(date);
    timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println("diff time format "+timeFormat.format(date));

Upvotes: 2

Related Questions