Posts Tagged ‘joda time’

Parsing Strings to DateTime (or LocalDate) using Joda time

Friday, November 27th, 2009

There’s no doubt that Joda time is now the defacto date time library for java. And a well written library it is. You get almost everything you can ever want to do with Date objects and best of all, almost all operations are dummy-proof. By dummy proof I mean that programmers making silly mistakes can’t really screw it up.

I recently had to parse a String into a LocalDate object using Joda time. I couldn’t find a parser in the docs or the very useful userguide but I knew it had to be possible, no one could overlook such a widely used operation. So I went in search of a parse.

It turns out that the parser and the formatter are one and the same thing in joda time, except with different methods ofcourse. Here’s how you construct a parser to parse a String in YYYYMMDD format :

DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder().appendYear(4, 4).appendMonthOfYear(2)
            .appendDayOfMonth(2).toFormatter();

(more…)