Change date format

If you enter 01-01-2015 , it should change to 2015-01-01 .
If the entry is 2015-01-01 , it should change to 01-01-2015 .
I used SimpleDateFormat but did not get the correct output:

 //Class to change date dd-MM-yyyy to yyyy-MM-dd and vice versa public class ChangeDate { static SimpleDateFormat formatY = new SimpleDateFormat("yyyy-MM-dd"); static SimpleDateFormat formatD = new SimpleDateFormat("dd-MM-yyyy"); //This function change dd-MM-yyyy to yyyy-MM-dd public static String changeDtoY(String date) { try { return formatY.format(formatD.parse(date)); } catch(Exception e) { return null; } } //This function change yyyy-MM-dd to dd-MM-yyyy public static String changeYtoD(String date) { try { return formatD.format(formatY.parse(date)); } catch(Exception e) { return null; } } } 

I need some condition that automatically determines the date template and changes it to another format.

+6
source share
5 answers

Regex is overkill

To work with the date, no need to worry about regex .

Just try to parse with one format, catching the expected exception. If an exception is actually thrown, try parsing with a different format. If an exception is thrown, then you know that the input is unexpectedly absent in any format.

java.time

You are using old inconvenient time classes, which are now superseded by the java.time framework built into Java 8 and later. The new classes are inspired by the highly successful Joda-Time framework, designed as its successor, similar to the concept, but re-created. Defined by JSR 310 . Extended in the ThreeTen-Extra project. See Oracle Tutorial .

LocalDate

New classes include one, LocalDate , for date values ​​only without the time of day. Just what you need.

Formatters

Your first format may be the standard format ISO 8601 , YYYY-MM-DD. This format is used by default in java.time.

If this first parsing attempt fails because the input is not in ISO 8601 format, a DateTimeParseException is DateTimeParseException .

 LocalDate localDate = null; try { localDate = LocalDate.parse( input ); // ISO 8601 formatter used implicitly. } catch ( DateTimeParseException e ) { // Exception means the input is not in ISO 8601 format. } 

Another format should be specified by a coded template, similar to what you do with SimpleDateFormat. Therefore, if we catch the exception on the first try, do the second parsing attempt.

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy" ); LocalDate localDate = null; try { localDate = LocalDate.parse( input ); } catch ( DateTimeParseException e ) { // Exception means the input is not in ISO 8601 format. // Try the other expected format. try { localDate = LocalDate.parse( input , formatter ); } catch ( DateTimeParseException e ) { // FIXME: Unexpected input fit neither of our expected patterns. } } 
+2
source

There are 2 options:

  • Try checking with the regular expression sth. as:

     if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) { ... } 
  • Try converting to the first pattern, if it throws an exception, try converting it to another pattern (but this is a bad way to do this)

+7
source

Read Pattern , Matcher and Regular Expressions .

Java code (based on OP):

 if (date.matches("\\d{2}-\\d{2}-\\d{4}")){ //convert D format to Y format... } else if(date.matches("\\d{4}-\\d{2}-\\d{2}")){ //convert Y to D... } else { throw new IllegalArgumentException("Received date format is not recognized."); } 

Note. This matching pattern can be improved with capture groups .
Example: "\\d{4}(-\\d{2}){2}" or "(-?\\d{2}){2}\\d{4}"

0
source

See: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/datetime/iso/examples/StringConverter.java

Non-ISO date conversion https://docs.oracle.com/javase/tutorial/datetime/iso/nonIso.html

Adding a new chronology that identifies an ISO date in any case is another compatible (punch) tool for entering date data and storing it in the correct structures (where other functions can easily work with the data). See: https://docs.oracle.com/javase/8/docs/api/java/time/chrono/Chronology.html

The "regex method" can be violated by erroneous input and does not leave any means to return a standard error in response to everything that was entered (to get a standard identical result everywhere).

See the answer provided by the user "Tardate" in this thread: How to check if the date is working in java .

You want to enter bulletproof input and store it in correctly identified structures to easily manipulate it with other functions.

0
source

Just compare the position of the first '-' character in the date string.

-2
source

All Articles