Purplemonkey
Purplemonkey

Reputation: 1967

Android: SimpleDateFormat keeps adding 1 hour to my time

I'm using currentTimeMillis(); to get a start time, then later using it again to get an end time. I then use delete start from end and get a value which is the duration between the two. I am using SimpleDateFormat to make all these values pretty and readable. the only thing is when i'm using a low value like 10 seconds (or 300 etc) and not the full blown long number (i.e. 1335718053126) I appear be getting out 01:00:10 or 01:02:12 etc on all my outputs? in fact if I just ask SimpleDateFormat to output a hh:mm:ss value against a 0 value it reads 01:00:00.

any one know why this is?

Found this neat little code if anyone else needs a solution to time formatting. Source link

public String getNiceTime(long time) {     

    String format = String.format("%%0%dd", 2);
    String seconds = String.format(format, time % 60);
    String minutes = String.format(format, (time % 3600) / 60);
    String hours = String.format(format, time / 3600);
    String outPutTime =  hours + ":" + minutes + ":" + seconds;
    return outPutTime;
}

Upvotes: 2

Views: 1594

Answers (1)

MariusBudin
MariusBudin

Reputation: 1287

mySimpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Explanation: you are probably living in a GMT+1 time zone and unless you specify a different one, your formatter will pick your current one, so it considers 0 hours as GMT and as you are in GMT+1, it outputs 1 hour

Upvotes: 2

Related Questions