Rajat Anantharam
Rajat Anantharam

Reputation: 505

LocalDate.toDate( ) returns inaccurate date

I am using JODA for formatting a Date of type : 2012-01-05T08:00:00.000Z (For the date 5th of Jan 2012) and trying to convert it to a Java Date.

The following are the steps which I am taking at this stage:

However while I should expect the returned date to be : 5th of Jan 2012, what I am getting is 1st of Jan 1970. I was under the impression that JODA takes care of these problems which the Java Date object is known to have.

Am I doing something wrong here - or do anyone of you have had similar issues and know a workaround to it?

Thanks Rajat

Edit:

Firstly thanks Michael.

So here is an improvement over my previous snippet which has made sure that I get the right Date - in other words the solution.

 
    //Make sure you use HH instead of hh if you are using 24 hour convention. I use this convention since my date format is: 2012-01-05T08:00:00.000Z


     DateTimeFormatter jodaParser = 
                 DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");

     LocalDate date = jodaParser.withZone(DateTimeZone.UTC).parseDateTime
                 (inputDateWhichIsAString).toLocalDate();

     return date.toDate();

Cheers Rajat

Upvotes: 3

Views: 1634

Answers (2)

Rajat Anantharam
Rajat Anantharam

Reputation: 505

Since we all like shorter solutions :

Considering my date format is one of type ISODateFormat as defined by JODA a much simpler solution to my problem would be :

DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dateTime = fmt.parseDateTime(inputDateWhichIsAString);
if (dateTime != null) {
    Date date = dateTime.toDate();
}
return date;

Upvotes: 0

poitroae
poitroae

Reputation: 21367

DateTimeFormat.forPattern expects, as the name suggests, a pattern instead of an input to convert from. Only DateTimeFormatter.parseDateTime(String) expects the String to parse the actual data.

So in DateTimeFormat.forPattern's String you have to pass a formatstring. Depending on your input, use the formatting symbols described here: http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html#forPattern(java.lang.String)

Upvotes: 3

Related Questions