• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

java.text.SimpleDateFormat does not behaves as expected

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic