Android : Converting time to "HH:mm:ss" using Calendar and SimpleDateFormat adds 1 hour

on Monday, October 27, 2014


Request


I need to convert time saved in seconds -> to "HH:mm:ss" (and other formats in the future).


E.g. 9 seconds -> "00:00:09".


However, the Calendar class always adds +1 hour. I assume it is because of my timezone (which is "Europe/Prague") or daylight savings time.


Testing


First simple usage of Date class. Then three times of Calendar with different timezones, trying methods setTimeInMillis() and set().



// Declarations
Calendar cal;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( format );
String result;


Date class usage:



// Simple Date class usage
Date date = new Date( timeInSecs * 1000 );
result = simpleDateFormat.format( date ); // WRONG result: "01:00:09"


Calendar class with "GMT":



// Calendar - Timezone GMT
cal = new GregorianCalendar( TimeZone.getTimeZone( "GMT" ) );

cal.setTimeInMillis( timeInSecs * 1000 );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"

cal.set( 1970, Calendar.JANUARY, 1, 0, 0, timeInSecs );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"


Calendar class with "UTC":



// Calendar - Timezone UTC
cal = new GregorianCalendar( TimeZone.getTimeZone( "UTC" ) );

cal.setTimeInMillis( timeInSecs * 1000 );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"

cal.set( 1970, Calendar.JANUARY, 1, 0, 0, timeInSecs );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"


Calendar class with "default" - "Europe/Prague":



// Calendar - Timezone "default" (it sets "Europe/Prague")
cal = new GregorianCalendar( TimeZone.getDefault() );

cal.setTimeInMillis( timeInSecs * 1000 );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"

cal.set( 1970, Calendar.JANUARY, 1, 0, 0, timeInSecs );
result = simpleDateFormat.format( cal.getTime() ); // CORRECT result: "00:00:09"


In the last case I got the right result but I do not understand why.


Questions



  1. Why the last case works? (And the one before doesn't?)

  2. How should I use the Calendar class to be able to simply pass time in seconds to it (without any parsing)?

  3. Is there another solution (another class)? Except for parsing it on my own.


0 comments:

Post a Comment