• Post Reply Bookmark Topic Watch Topic
  • New Topic

java.text.SimpleDateFormat does not behaves as expected  RSS feed

 
ajinkyad desai
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
See the following code

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
sdf.setLenient(false);
Date st = sdf.parse("04-12-2000sdfsdfsf"); System.out.println(st);

It will produce output as

Mon Dec 04 00:00:00 IST 2000

instead of throwing ParseException and also if I give

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
sdf.setLenient(false);
Date st = sdf.parse("04-12-200046649sdfsdfsf");
System.out.println(st);

It will produce output as

Tue Dec 04 00:00:00 IST 200046649

It ignores trailing non-numeric characters of last field.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even when you call setLenient(false) on the SimpleDateFormat object, it isn't really strict with checking the format of the input string. Unfortunately the API documentation doesn't exactly specify the difference between setting lenient to true or false.

If you want to check if the input string matches a certain format exactly, you could use a regular expression to check it before you parse it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!