cruftex
cruftex

Reputation: 5723

Easy and fast way to format a timestamp

We have some timestamps represented as long in millis since epoch. Within strings for logging, exceptions, or toString() methods, these timestamps need to be formatted. A simple and clean format is enough.

So, what is the simplest and fastest method for formatting a timestamp in Java?

Requirements:

In particular, did somebody did a benchmark of JDK methods that can be used for this?

Actually I don't want to use SimpleDateFormat, since I believe its flexibility comes with too much overhead.

Upvotes: 2

Views: 2796

Answers (4)

rmuller
rmuller

Reputation: 12859

Easy to use and reasonable fast:

// All Java versions:
new java.sql.Timestamp(millis).toString(); // 2016-10-29 12:28:41.979

// Recommended when using Java 8+ (about +50% faster than Timestamp), standards compliant format
// checked with jmh 1.15
java.time.Instant.ofEpochMilli(millis).toString(); // 2016-10-29T10:28:41.979Z

Upvotes: 3

Fevly Pallar
Fevly Pallar

Reputation: 3099

Apache Commons Lang's FastDateFormat class is absolutely a good alternative to SimpleDateFormat. It's fast and also Thread-Safe ( especially usefull in multi-threaded server environments). All patterns are compatible with SimpleDateFormat (except time zones and some year patterns).

The summary of the constructor is :

FastDateFormat(String pattern, TimeZone timeZone, Locale locale)

You could find more info at FastDateFormat

Upvotes: 1

Joe
Joe

Reputation: 31087

The fastest implementation is very likely to be:

Long.toString(millis);

If performance is the most important thing, you should use that.

Actually I don't want to use SimpleDateFormat, since I believe its flexibility comes with too much overhead.

According to a quick jmh benchmark, on my laptop, Long.toString gets twelve million ops/second and SimpleDateFormat is two million.

What's your budget? Once you know that you'll be able to decide which of those is most appropriate.

Upvotes: 1

erikvimz
erikvimz

Reputation: 5476

Try:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeStamp);

Or:

Date date = new Date(milliseconds);

Not sure which one is faster though.

To format the Date into a string, you can use SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss.SSS"); // should output something like you desired: 20141220 174522.23
String formattedDate = sdf.format(date); 

Upvotes: 0

Related Questions