Reputation: 3456
I want to display months with the names. So i'm using JODA.jar
This is my code :
public static void main(String[] args) {
String date1 = "2013-21-01 14:00:00";
String date2 = "2013-01-01 14:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date date11, date22;
try {
date11 = sdf.parse(date1);
System.out.println("Date : " +date11);
date22 = sdf.parse(date2);
System.out.println("Date : " +date22);
DateTime dt1 = new DateTime(date11);
String monthName1 = dt1.monthOfYear().getAsText(Locale.ENGLISH);
DateTime dt2 = new DateTime(date22);
String monthName2 = dt2.monthOfYear().getAsText(Locale.ENGLISH);
System.out.println("String1 : " +monthName1+" "+dt1.getYear());
System.out.println("String2 : " +monthName2+" "+dt2.getYear());
}
catch (ParseException e) {
e.printStackTrace();
}
}
In the first date, I put 21 like month, this is not possible. But I have this in the Console :
Date : Mon Sep 01 14:00:00 GMT+01:00 2014
Date : Tue Jan 01 14:00:00 GMT+01:00 2013
String1 : September 2014
String2 : January 2013
How it can be like this ? Normally it shouldn't show the first date, just the right date, right ?
Upvotes: 2
Views: 247
Reputation: 11
21 is 12+9 so by entering this you added 1 year to the date you wanted to set actually.
Upvotes: 0
Reputation: 280178
It's currently rolling over to the next year.
21 - 12 = 9 = September
So that it doesn't rollover, just make it non-lenient
sdf.setLenient(false);
Upvotes: 6
Reputation: 7411
Java date parsing is referred to as lenient
- it allows parsing of dates that aren't technically valid, and works out what the user may have been referring to.
In this particular case, it's seen month 21 of 2013, assumed that the user was being lazy in incrementing months, and taken it to mean month 9 of 2014 - September.
More information on leniency can be found in the Java documentation.
Upvotes: 1