Convert timestamp in milliseconds to string formatted time in Java

Cratylus picture Cratylus · Nov 10, 2010 · Viewed 310.8k times · Source

I am trying to convert a long value (number of milliseconds elapsed from 1/1/1970 i.e. Epoch) to time of format h:m:s:ms.

The long value I use as timestamp, I get from the field timestamp of a logging event from log4j.

So far I've tried the following and it fails:

logEvent.timeStamp/ (1000*60*60)
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

but I get incorrect value:

1289375173771 for logEvent.timeStamp
358159  for logEvent.timeStamp/ (1000*60*60) 
21489586 for TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

How do I go about this?

Answer

manolowar picture manolowar · Nov 10, 2010

Try this:

Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);

See SimpleDateFormat for a description of other format strings that the class accepts.

See runnable example using input of 1200 ms.