scout
scout

Reputation: 2386

JodaTime: parsing dates with leading hyphens

With JodaTime

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(DateTimeZone.UTC);
java.util.Date parsedDate = dtf.parseDateTime("-012-10-25T10:03:22Z").toDate();

System.out.println(parsedDate)

prints

'Tue Oct 27 04:03:22 CST 13'

As you can tell, the local timeZone is CST.

I expect an exception to be thrown as the date that is passed is not in the expected format. or may be a NumberFormatException for, '-' is not a number

Upvotes: 0

Views: 599

Answers (1)

Ilya
Ilya

Reputation: 29693

Joda supports years before zero (see DateTimeConstants.BC that means Before Christ).
So -012-10-25T10:03:22Z is treated by Joda like 12 years B.C.

DateTime d = dtf.parseDateTime("-012-10-25T10:03:22Z");
System.out.println(d.getEra()); // returns 0 -> that means B.C. era Before Christ
System.out.println(d.getYear()); // returns -12  

if you want throw exception, then you should do it manualy, becouse Joda doesn't throws exception in this case. Do somethid like

   DateTime dateTimeParser(String dateAsString)  
   {  
      DateTime res = dtf.parseDateTime(dateAsString);
      if (d.getYear() < 0) throw new IllegalArgumentException();  
      return res;  
   } 

Or use SimpleDateFormat to parse Date

Upvotes: 3

Related Questions