Thomas Johnson Thomas Johnson - 4 months ago 17
Java Question

How can I convert seconds since the epoch to hours/minutes/seconds in Java?

Is there a fast, low-garbage way to do it? I can't just do simple modulus arithmetic since that doesn't account for leap seconds and other date/time funny business.

Answer

This is a fast, zero-garbage solution. It is of key importance not to create a new instance of Calendar on each call because it's quite a heavyweight object, taking 448 bytes of heap and almost a microsecond to initialize (Java 6, 64-bit HotSpot, OS X).

HmsCalculator is intended for use from a single thread (each thread must use a different instance).

public class HmsCalculator
{
  private final Calendar c = Calendar.getInstance();

  public Hms toHms(long t) { return toHms(t, new Hms()); }
  public Hms toHms(long t, Hms hms) {
    c.setTimeInMillis(t*1000);
    return hms.init(c);
  }
  public static class Hms {
    public int h, m, s;
    private Hms init(Calendar c) {
      h = c.get(HOUR_OF_DAY); m = c.get(MINUTE); s = c.get(SECOND);
      return this;
    }
    public String toString() { return String.format("%02d:%02d:%02d",h,m,s); }
  }

  public static void main(String[] args) {
    System.out.println(new HmsCalculator().toHms(
       System.currentTimeMillis()/1000));
  }
}

P.S. I didn't paste all those static imports (boring).

Comments