Convert timestamp in milliseconds to string formatted time in Java

JavaDatetimeTimeTimestampEpoch

Java Problem Overview


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?

Java Solutions


Solution 1 - 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.

Solution 2 - Java

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);

Solution 3 - Java

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 api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);

Joda-Time

// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final 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

Solution 4 - Java

It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

For example:

String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"

Hope it can help ...

Solution 5 - Java

long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);

Solution 6 - Java

public static String timeDifference(long timeDifference1) {
long timeDifference = timeDifference1/1000;
int h = (int) (timeDifference / (3600));
int m = (int) ((timeDifference - (h * 3600)) / 60);
int s = (int) (timeDifference - (h * 3600) - m * 60);

return String.format("%02d:%02d:%02d", h,m,s);

Solution 7 - Java

Try this:

	String sMillis = "10997195233";
	double dMillis = 0;
	
	int days = 0;
	int hours = 0;
	int minutes = 0;
	int seconds = 0;
	int millis = 0;
	
	String sTime;
	
	try {
		dMillis = Double.parseDouble(sMillis);
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
	
	
	seconds = (int)(dMillis / 1000) % 60;
	millis = (int)(dMillis % 1000);
	
	if (seconds > 0) {
		minutes = (int)(dMillis / 1000 / 60) % 60;
		if (minutes > 0) {
			hours = (int)(dMillis / 1000 / 60 / 60) % 24;
			if (hours > 0) {
				days = (int)(dMillis / 1000 / 60 / 60 / 24);
				if (days > 0) {
					sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
				} else {
					sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
				}
			} else {
				sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
			}
		} else {
			sTime = seconds + " sec " + millis + " millisec";
		}
	} else {
		sTime = dMillis + " millisec";
	}
	
	System.out.println("time: " + sTime);

Solution 8 - Java

Doing

logEvent.timeStamp / (1000*60*60)

will give you hours, not minutes. Try:

logEvent.timeStamp / (1000*60)

and you will end up with the same answer as

TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

Solution 9 - Java

long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
long seconds = TimeUnit.MILLISECONDS.toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);

return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

Solution 10 - Java

I wanted to only show the relevant part of the time. So, always show seconds, but only show minutes/hours/days if there are any.

Also, optionally show milliseconds.

And I was using GWT, so I couldn't use String.format.

So, if this is you too, here is the code.

public static String formatTimeFromMs(long timeInMs, boolean showMs) {
	boolean negative = timeInMs < 0;

	timeInMs = Math.abs(timeInMs);

	StringBuffer result = new StringBuffer();
	long seconds = (timeInMs / 1000) % 60;
	long minutes = (timeInMs / (1000 * 60)) % 60;
	long hours = (timeInMs / (1000 * 60 * 60)) % 24;
	long days = (timeInMs / (1000 * 60 * 60 * 24));

	if (days > 0) {
		result.append(days + "d ");
	}
	
	if (hours > 0) {
		if (hours < 10 && result.length() > 0) {
			result.append("0");
		}
		result.append(hours + ":");
	}
	else if (result.length() > 0) {
		result.append("00:");
	}

	if (minutes > 0) {
		if (minutes < 10 && result.length() > 0) {
			result.append("0");
		}
		result.append(minutes + ":");
	}
	else if (result.length() > 0) {
		result.append("00:");
	}

	if (seconds > 0) {
		if (seconds < 10 && result.length() > 0) {
			result.append("0");
		}
		result.append(seconds);
	}
	else if (result.length() > 0) {
		result.append("00");
	}
	else {
		result.append("0");
	}

	if (showMs) {
		long millis = timeInMs % 1000;
		
		if (millis < 10) {
			result.append(".00" + millis);
		}
		else if (millis < 100) {
			result.append(".0" + millis);
		}
		else {
			result.append("." + millis);
		}
	}

	if (negative) {
		result.insert(0, "-");
	}

	return result.toString();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCratylusView Question on Stackoverflow
Solution 1 - JavamanolowarView Answer on Stackoverflow
Solution 2 - JavaBrajendra PandeyView Answer on Stackoverflow
Solution 3 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 4 - JavaYoChaView Answer on Stackoverflow
Solution 5 - JavaLo KaView Answer on Stackoverflow
Solution 6 - JavaVivek PalView Answer on Stackoverflow
Solution 7 - JavaLeoZaoView Answer on Stackoverflow
Solution 8 - JavaNico HuysamenView Answer on Stackoverflow
Solution 9 - JavaJoel Richard KoettView Answer on Stackoverflow
Solution 10 - JavaCraigoView Answer on Stackoverflow