Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to parse a date strictly?

Tags:

SimpleDateFormat is a very kind parser that rolls the resulting date instead of throwing an error. How can I parse a date strictly without regexps etc?

fmt = new SimpleDateFormat("dd.MM.yyyy") fmt.parse("10.11.2012")   // it works fmt.parse("10.1150.2012") // it works but it's unwanted 
like image 432
Pavel Vlasov Avatar asked Oct 26 '12 13:10

Pavel Vlasov


People also ask

How do you parse a date object in Java?

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly): SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

How do you parse a date?

The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.


1 Answers

fmt.setLenient(false); is what you're looking for.

like image 112
sp00m Avatar answered Nov 08 '22 23:11

sp00m