kiran
kiran

Reputation: 2428

Java SimpleDateFormat

I want to convert a date which may be several formats like yyyyMMdd,yyyy-MM-dd,yyyy/MM/dd to a standard for 'yyyy-MM-dd HH:mm:ss'. In the below code, I set the expected date format to 'yyyyMMdd' and then passed in '2014-02-21'. I was expecting a Parse Exception but some how this is returning '2013-12-02 00:00:00'.What am I missing here ?

SimpleDateFormat sdfSource = new SimpleDateFormat("yyyyMMdd");
Date date = sdfSource.parse("2014-02-21");
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println( sdfDestination.format(date));

Upvotes: 0

Views: 673

Answers (2)

PbxMan
PbxMan

Reputation: 7625

The lenient property is set to true by default. here

sdfSource.setLenient(false);

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

I would recommend adding sdfSource.setLenient(false); between the first two lines of that snippet.

What's happening here is that "-0" is being interpreted as the month, and "2" as the day. With leniency true (which is the default) this is acceptable - "-0" is interpreted as the month before the first month; that is "December of the previous year".

Upvotes: 3

Related Questions