Analysis of time by date, adopted 05/05/1999 and 5/5/1999, etc.

Is there an easy way to parse a date, which could be in MM / DD / yyyy, or M / D / yyyy, or some combination? those. zero is optional up to one day or month sign.

To do this manually, you can use:

String[] dateFields = dateString.split("/"); int month = Integer.parseInt(dateFields[0]); int day = Integer.parseInt(dateFields[1]); int year = Integer.parseInt(dateFields[2]); 

And confirm with:

 dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d") 

Is there a call to SimpleDateFormat or JodaTime to handle this?

+4
source share
3 answers

It seems like my problem was using "MM / DD / yyyy" when I was supposed to use "MM / dd / yyyy". Uppercase D is Day after Year, and lowercase d is Day after Month.

 new SimpleDateFormat("MM/dd/yyyy").parse(dateString); 

Does it work. In addition, "M / d / y" works interchangeably. A more detailed description of the SimpleDateFormat API Documents shows the following:

"For parsing, the number of letters in the patterns is ignored unless you want to separate two adjacent fields."

+1
source

Yes, use setLenient:

 DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); df.setLenient(true); System.out.println(df.parse("05/05/1999")); System.out.println(df.parse("5/5/1999")); 
+10
source

java.time

Java 8 and later include the java.time framework. This structure deprecates the old java.util.Date/.Calendar classes discussed in other answers here.

The java.time.format package and its java.time.format.DateTimeFormatter class use template codes similar to those discussed in the accepted answer from Ray Myers. Although they are similar, they vary a little. In particular, they are strict regarding the number of repeated characters. If you say MM , then the month should have a zero plus, otherwise you will get a DateTimeParseException . If the month number may or may not have a zero space, just use the single-character M

In this code example, notice how the month number of the input line has a zero space and the day number of the month does not. Both are handled by a single character pattern.

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M/d/yyyy" ); LocalDate localDate = formatter.parse ( "01/2/2015" , LocalDate :: from ); 

Dump for the console.

 System.out.println ( "localDate: " + localDate ); 

localDate: 2015-01-02

+2
source

All Articles