Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good date parser for Java?

Tags:

Does anyone know a good date parser for different languages/locales. The built-in parser of Java (SimpleDateFormat) is very strict. It should complete missing parts with the current date.

For example

  • if I do not enter the year (only day and month) then the current year should be used.
  • if the year is 08 then it should not parse 0008 because the current year pattern has 4 digits.

Edit: I want to parse the input from a user. For example if the locale date format of the user is "dd.mm.yyyy" and the user type only "12.11." then the parser should accept this as a valid date with the value "12.11.2008". The target is a good usability.

like image 679
Horcrux7 Avatar asked Oct 21 '08 15:10

Horcrux7


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 I parse a date in a specific format?

Instantiate the SimpleDateFormat class by passing the desired (new) format as string to its constructor. Invoke the format() method by passing the above obtained Date object as parameter.

What does SimpleDateFormat parse do?

The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.

Can we convert string to date in Java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.


2 Answers

Check Joda Time, and its Freaky Formatters.

Java 8 includes JSR-310 so that could be a solution as well.

like image 191
Petteri H Avatar answered Oct 07 '22 00:10

Petteri H


From 43642, although not necessarily a duplicate:

See Apache Commons' DateUtils. There's a parseDate method that takes your String and multiple patterns to try and spits out a Date instance.

like image 33
Joe Liversedge Avatar answered Oct 07 '22 00:10

Joe Liversedge