<< How can I get all classes in a specific package? | Home | How do I send mail with Java? >>

How do I parse or format dates? Dates are hard!

Well, Barbie, dates are really pretty easy. Here's a class (ParseDate.java) with a number of formatting and parsing examples, with java.util.* and Joda-Time.

ParseDate has two properties: a formatter and a parser. The ParseDate.java has the definitions of the formatter and parser interfaces immediately following the ParseDate class itself.

A Formatter is designed to yield a String, which contains the textual representation of the instant (milliseconds since the epoch) passed to it.

A parser takes a String and converts it to an instant.

There are two parsers and three formatters also appended to the source file: one parser uses Joda-Time to parse the date, the other uses java.util.SimpleDateFormat.

The formatters use Joda-Time, SimpleDateFormat, and a brute force StringWriter (pulling data from Calendar directly) to format the instant into a String.

So: if you want to know how to parse a String into a Date, check out the various parser implementations; if you're trying to print a date into a human-readable string, check out the formatters.

Say... I thought Barbie always had a date...




Add a comment Send a TrackBack