Reputation: 1040
I am getting different date formats below dd-MM-yyyy,dd/MM/yyyy
,yyyy-MM-dd
,yyyy/MM/dd
SimpleDateFormat sm1 = new SimpleDateFormat("dd-MM-yyyy");
String date = "01-12-2013";
System.out.println("Date 1 is "+sm1.parse(date));
date = "2013-12-01";
System.out.println("Date 1 is "+sm1.parse(date));
the same simple date format gives the below result eventhough date format is wrong(ie:-2013-12-01).Below the results.
Date 1 is Sun Dec 01 00:00:00 IST 2013
Date 1 is Sun Jun 05 00:00:00 IST 7
Upvotes: 2
Views: 161
Reputation: 7
I have tried Jigar Joshi's answer. ==========================code=======================================
SimpleDateFormat sm1 = new SimpleDateFormat("dd-MM-yyyy");
sm1.setLenient(false);
String date = "01-12-2013";
System.out.println("Date 1 is "+sm1.parse(date));
date = "2013-12-01";
System.out.println("Date 1 is "+sm1.parse(date));
=========================Result========================================
Date 1 is Sun Dec 01 00:00:00 CST 2013
Exception in thread "main" java.text.ParseException: Unparseable date: "2013-12-01"
at java.text.DateFormat.parse(DateFormat.java:337)
at workflow.Test.main(Test.java:14)
Upvotes: 1
Reputation: 106430
Your date format is dd-MM-yyyy
. That means the parser is expecting some day, month, and year format.
From the SimpleDateFormat
documentation: the number of pattern letters in a Number
type formatter is the minimum. So, while 2013
wouldn't make sense in our mind, it fits within the formatter's bounds.
You have provided 2013-12-01
as to fit into that format. What it appears the formatter is doing is providing December 1 (insert timezone here), and then adding 2,013 days to it.
That turns out to be June 6, 7 AD. There's some wiggle room for your timezone (I'm not sure which of the five timezones IST represents is actually yours).
So, believe it or not...the formatter is correct. Be very careful as to what kind of format you specify or allow in your dates!
If you don't want that parsed, then specify setLenient(false)
on your instance of sm1
.
Upvotes: 0
Reputation: 240900
You need to setLenient(false)
to make parse()
method throw
ParseException
for unparsable case
Upvotes: 5