String based date format selection

I have a class that gets Date in string format from another class. Now he gets 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 that receives this string and converts it to the required format, like this "DDMMMYYYY"

+4
source share
2 answers

You can try brute force to make out exceptions:

Edit

using java8 API (adapt the format as you like)

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 older 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 specify any other invalid string, the returned string will be empty!

+4
source

:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy_MM_dd][EEE MMM dd HH:mm:ss Z yyyy]", Locale.ENGLISH);

formatter , .

P.S. , , EEE MMM dd HH:mm:ss Z yyyy. Java 8 (Java Time)

+3

Source: https://habr.com/ru/post/1678320/


All Articles