Parsing Strings to DateTime (or LocalDate) using Joda time

November 27th, 2009 | Tags:

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


Once you have a formatter, you can pass a string and get a DateTime object in return:

DateTime time = inputFormatter.withZone(DateTimeZone.UTC).parseDateTime("20090607");

You can see that the formatter allows you to specify a time zone while performing the conversion. This is very handy because you don’t have to create a new formatter every time you want to use a different time zone.

And we finally convert this to LocalDate:

LocalDate date = inputFormatter.withZone(DateTimeZone.UTC).parseDateTime("20090607").toLocalDate();

I just want to add that if you have ever had to parse strings into dates and times, you should really go check out joda time and it’s parsing capabilities (if you haven’t already). It opens up a whole new dimension of clean date/time code.

Share and Enjoy:
  • del.icio.us
  • Google Bookmarks
  • DZone
  • Reddit
  • Digg
  • Facebook
  • Netvibes
  • StumbleUpon
  • Technorati
  • LinkedIn
  • MySpace
  • Print
  • Slashdot
  • Share/Bookmark

No related posts.

  1. November 27th, 2009 at 17:10
    Reply | Quote | #1

    The next version of Joda-Time will have a parseLocalDate() method.

    • Gaurav Arora
      November 27th, 2009 at 22:25
      Reply | Quote | #2

      Good to know. Looking forward to the next release. :)

  2. March 17th, 2010 at 01:22
    Reply | Quote | #3

    dude u stopped blogging?