Java – change date format
If the input is 01-01-2015, it should be changed to 2015-01-01
//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 want some conditions to automatically detect date patterns and change to other formats
Solution
Regular expressions are overkill
For date and time work, you don't need to disturb regex
Just try to parse in one format to catch the expected exception If you do throw an exception, try parsing in a different format If you throw an exception, you know that the input is unexpectedly not in two formats
java. time
You are using @ L, which is now built into Java 8 and later_ 404_ 1 @ framework replaces the old troublesome datetime class The new curriculum is inspired by the very successful joda time framework, which is designed to be its successor, similar in concept but redesigned Defined by JSR 310 Extended by threeten extra project See Oracle tutorial
Of localdate
The new class includes a localdate, which is only applicable to date values without time That's what you need
Formatter
Your first format may be the standard ISO 8601 format, yyyy-mm-dd. by default, this format is used for Java time.
If the first parsing attempt fails because the input does not match the ISO 8601 format, a datetimeparseexception is thrown
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. }
The other format must be specified by an encoding scheme similar to what you use simpledateformat Therefore, if we catch an exception from the first attempt, please make a 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. } }