Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Date format based on the string [duplicate]

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 '

like image 341
Raj Avatar asked Mar 08 '23 23:03

Raj


2 Answers

You can try brute force to parse catching the exceptions:

edit:

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!

like image 146
ΦXocę 웃 Пepeúpa ツ Avatar answered Mar 18 '23 09:03

ΦXocę 웃 Пepeúpa ツ


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)

like image 36
Andriy Rymar Avatar answered Mar 18 '23 09:03

Andriy Rymar