HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java Date formatter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formatterjavadate

Problem

The (real life) problem

Following my question on SO, I found out that printing a Java Date() in a custom format is quite tedious:

final Date date = new Date();
final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));


I was looking for a one-liner without object initialization:

System.out.println(magic(date, "yyyy-MM-dd'T'HH:mm:ss.SSS zzz", "UTC"));


My Solution

PrettyDate class, which formats Date() objects using TimeZones and Formats given as strings, sans any external object creation. There are some convenience methods for popular timezone\format combinations.

Alternatives to Consider (please comment on these, too!)

  • Extending Date() with better toString()



  • Using non-static methods: Initializing PrettyDate with a Format and a TimeZone, and feeding it with Date objects to get a string representation



Usage

// The problem - not UTC
Date.toString()
"Tue Jul 03 14:54:24 IDT 2012"

// ISO format, now
PrettyDate.now()
"2012-07-03T11:54:24.256 UTC"

// ISO format, specific date
PrettyDate.toString(new Date())
"2012-07-03T11:54:24.256 UTC"

// Legacy format, specific date
PrettyDate.toLegacyString(new Date())
"Tue Jul 03 11:54:24 UTC 2012"

// ISO, specific date and time zone
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd hh:mm:ss zzz", "CST")
"1969-08-20 03:17:40 CDT"

// Specific format and date
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
"1969-08-20"

// ISO, specific date
PrettyDate.toString(moonLandingDate)
"1969-08-20T20:17:40.234 UTC"

// Legacy, specific date
PrettyDate.toLegacyString(moonLandingDate)
"Wed Aug 20 08:17:40 UTC 1969"


Code

```
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
* Formats dates to sortable UTC strings in compliance with ISO-8601.

Solution

Also be aware that SimpleDateFormat is not thread-safe. In a Multithreading Environment users should create a separate instance for each thread. For more information how to achieve it check this link

Context

StackExchange Code Review Q#13283, answer score: 8

Revisions (0)

No revisions yet.