Convert timestamp in milliseconds to string formatted time in Java Convert timestamp in milliseconds to string formatted time in Java java java

Convert timestamp in milliseconds to string formatted time in Java


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.


long millis = durationInMillis % 1000;long second = (durationInMillis / 1000) % 60;long minute = (durationInMillis / (1000 * 60)) % 60;long hour = (durationInMillis / (1000 * 60 * 60)) % 24;String time = String.format("%02d:%02d:%02d.%d", hour, minute, second, millis);


I'll show you three ways to (a) get the minute field from a long value, and (b) print it using the Date format you want. One uses java.util.Calendar, another uses Joda-Time, and the last uses the java.time framework built into Java 8 and later.

The java.time framework supplants the old bundled date-time classes, and is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

The java.time framework is the way to go when using Java 8 and later. Otherwise, such as Android, use Joda-Time. The java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

java.util.Date & .Calendar

final long timestamp = new Date().getTime();// with java.util.Date/Calendar apifinal Calendar cal = Calendar.getInstance();cal.setTimeInMillis(timestamp);// here's how to get the minutesfinal int minutes = cal.get(Calendar.MINUTE);// and here's how to get the String representationfinal String timeString =    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());System.out.println(minutes);System.out.println(timeString);

Joda-Time

// with JodaTime 2.4final DateTime dt = new DateTime(timestamp);// here's how to get the minutesfinal int minutes2 = dt.getMinuteOfHour();// and here's how to get the String representationfinal String timeString2 = dt.toString("HH:mm:ss:SSS");System.out.println(minutes2);System.out.println(timeString2);

Output:

24
09:24:10:254
24
09:24:10:254

java.time

long millisecondsSinceEpoch = 1289375173771L;Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );String output = formatter.format ( zdt );System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );

millisecondsSinceEpoch: 1289375173771 instant: 2010-11-10T07:46:13.771Z output: 07:46:13:771