Search code examples
javatimedate-formathour

Zero-pad hour in DateFormat


I am trying to display a time difference into a string which follows the form 00:00:00 (hours:minutes:seconds), zero-padded. I have the following code:

long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
time = DateFormat.format("hh:mm:ss", timeDiff).toString(); 

I was testing it when the timeDiff was no more than a few seconds but the hour does not show as 00. I am in the JST timezone by the way.


Solution

  • Where did you get mStartRecordingTime? It doesn't look to me like it was set with System.currentTimeMillis() in the same locale; if it had been, then the time difference would have reflected the actual difference and this would have worked. It appears that the recording time somehow got set with UTC, 9 hours away from JST.

    The other poster is correct, a date produced with this value would be near epoch, but if you're just trying to get hours, minutes, and seconds, then you should be all right. Keep in mind that you're dealing with elapsed time, not clock/calendar time, so I wouldn't expect the date formatting (as opposed to time formatting) things to work for you.