I have class which receives Date in string format from other class. It is now receiving two different formats
Format 1: YYYY_MM_DD
Format 2: EEE MMM dd HH:mm:ss z yyyy
now I want to write a method which receives this string and convert it into required format like this 'DDMMMYYYY '
You can try brute force to parse catching the exceptions:
using the java8 API (adapt the format as you need/want)
public String convertDateFormatJ8(String format) {
String retFormat = "ddMMyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_dd_MM][yyyy-MM-dd HH:mm]");
try {
LocalDateTime localDate = LocalDateTime.parse(format, formatter);
return localDate.format(DateTimeFormatter.ofPattern(retFormat));
} catch (DateTimeParseException ex) {
System.err.println("impossible to parse to yyyy-MM-dd HH:mm");
}
try {
LocalDate localDate = LocalDate.parse(format, formatter);
return localDate.format(DateTimeFormatter.ofPattern(retFormat));
} catch (DateTimeParseException ex) {
System.err.println("impossible to parse to yyyy_dd_MM");
}
return null;
}
for old java versions
public String convertDateFormat(String format) {
DateFormat df1 = new SimpleDateFormat("YYYY_MM_DD");
DateFormat df2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
DateFormat dfResult = new SimpleDateFormat("DDMMMYYYY ");
Date d = null;
try {
d = df1.parse(format);
return dfResult.format(d);
} catch (ParseException e) {
System.err.println("impossible to parse to " + "YYYY_MM_DD");
}
try {
d = df2.parse(format);
return dfResult.format(d);
} catch (ParseException e) {
System.err.println("impossible to parse to " + "EEE MMM dd HH:mm:ss z yyyy");
}
return null;
}
if you give any other invalid string, the string returned will be null!
You can use this approach and declare optional section in pattern :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_MM_dd][EEE MMM dd HH:mm:ss Z yyyy]", Locale.ENGLISH);
This formatter
will parse date for both patterns and then you can easily convert it to required format.
P.S. I've tested it but not sure which date should be parsable for EEE MMM dd HH:mm:ss Z yyyy
template. So just play with it and use Java 8 approaches (Java Time)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With