Kris B
Kris B

Reputation: 3578

Joda Invalid format exception

I'm trying to convert a string from to a Joda DateTime object. The date is coming from a SQLlite datefield, eg:

 2011-11-19 18:29:41

The code I'm using is:

 DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("2011-11-19 18:29:41").withZone(DateTimeZone.getDefault());

but I'm getting this exception:

 java.lang.IllegalArgumentException: Invalid format: "2011-11-19 18:29:41" is malformed at "11-11-19 18:29:41"

EDIT: here is more details in what I'm doing:

I have a utility class, which has a method I'm using to convert strings to DateTime:

public static DateTime GetItemDate(final String date, String pattern)
{
    return DateTimeFormat.forPattern(pattern).parseDateTime(date).withZone(DateTimeZone.getDefault());
}

Then I call:

 Utilities.GetItemDate("2011-11-19 18:29:41", "YYYY-MM-dd HH:mm:ss");

Upvotes: 2

Views: 8685

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503839

Both the patterns you've given actually work for me (I've taken the liberty of making the method name follow Java naming conventions, but the body is the same).

It's worth nothing that the patterns are different though - "y" is "year" (which could be negative) whereas "Y" is "year of era".

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        // Works
        DateTime dateTime = getItemDate("2011-11-19 18:29:41",
                                        "yyyy-MM-dd HH:mm:ss");

        System.out.println(dateTime);

        // Works for me too...
        dateTime = getItemDate("2011-11-19 18:29:41",
                               "YYYY-MM-dd HH:mm:ss");

        System.out.println(dateTime);
    }

    public static DateTime getItemDate(String date, String pattern) {
        return DateTimeFormat.forPattern(pattern)
            .parseDateTime(date)
                .withZone(DateTimeZone.getDefault());
    }
}

Output on my machine:

2011-11-19T18:29:41.000Z
2011-11-19T18:29:41.000Z

I'd actually suggest that you specify the time zone for the formatter too - as otherwise it's going to use the default time zone already.

What locale are you in? Perhaps that's causing a problem...

Upvotes: 4

Related Questions