Home > front end >  Convert Date in String type of one format to String type in another Date format [closed]
Convert Date in String type of one format to String type in another Date format [closed]

Time:10-04

I have a use case where I need to change the date format in Java. The input date will be in the form of String and the output format required is also a String.

Input_Date can be in any of the form (yyyy-MM-dd):

  • 2021-08-30&2021-09-16
  • 2021-08-30

Output_Date would be:

  • August 30,2021-September 16, 2021
  • August 30,2021

CodePudding user response:

Two situations:

  1. a single date String is to be reformatted and
  2. a single String containing two (or more?) concatenated dates separated by ampersand(s), too

I would first define a java.time.format.DateTimeFormatter needed to create the desired output (I chose a class constant here):

public static final DateTimeFormatter FORMATTER =
                        DateTimeFormatter.ofPattern("MMMM dd,uuuu", Locale.ENGLISH);

Make sure you provide a Locale to the DateTimeFormatter, otherwise it will take the default locale, which might produce output in undesired formats and languages.

The first one is pretty straight-forward from Java 8 on when java.time.LocalDate.parse(String s) is used, because you only have to use a formatter you defined before in LocalDate.format(DateTimeFormatter formatter) (code example included below).

The second one needs more processing, I think you have to split the input, parse each date contained, reformat each one and concatenate the results to a single String using hyphons as separators.

Handling the multi-date String:

public static String convertConcatDates(String concatenatedDates) {
    // split the input by ampersand first
    String[] splitInput = concatenatedDates.split("&");
    // convert all / both of the dates to LocalDates in a list
    List<LocalDate> dates = Arrays.stream(splitInput)
                                  .map(LocalDate::parse)
                                  .collect(Collectors.toList());
    // create a list of each date's month and day of month
    List<String> daysAndMonths = new ArrayList<String>();
    // get each date as formatted String
    dates.forEach(date -> daysAndMonths.add(date.format(FORMATTER)));
    // then concatenate the formatted Strings and return them as a single one
    return String.join("-", daysAndMonths);
}

Example main showing both reformattings:

public static void main(String[] args) throws IOException {
    /*
     *  (1) example for a single date String
     */
    String single = "2021-08-30";
    // parse the date (no pattern needed if input is ISO standard)
    LocalDate singleLd = LocalDate.parse(single);
    // print the result in the desired format
    System.out.println(singleLd.format(FORMATTER));
    
    /*
     * (2) example for concatenated date Strings
     */
    String concat = "2021-08-30&2021-09-16";
    // call the method and print the result
    System.out.println(convertConcatDates(concat));
}

Output:

August 30,2021
August 30,2021-September 16,2021

CodePudding user response:

I worked on a similar project where I needed to be able to parse ANY String that possibly could be parsed to a Date. The solution was something like this: I created a property file that contained in a list all Date Formats that I wanted to support. Then when a String came I took the list of formats one by one trying to parse the incoming String until it worked or until I ran out of formats. The solution could be flexible where for different clients you could have a different list of formats and also, you could switch the order and thus control wether US or European formats can take precedence. The solution is described in more detail in this article: Java 8 java.time package: parsing any string to date

CodePudding user response:

You can use SimpleDateFormat for this.

public static String convertPattern(String dateString, String inPattern, String outPattern) {
    SimpleDateFormat format = new SimpleDateFormat(inPattern);
    try {
        Date date = format.parse(dateString);
        format.applyPattern(outPattern);
        return format.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}

This is how you can use this,

convertDate("2021-10-03", "yyyy-MM-dd", "MMMM dd, yyyy");

Update

You can do the same with DateTimeFormatter as well.

public static String convertPattern(String dateString, String inPattern, String outPattern) {
    DateTimeFormatter inFormat = DateTimeFormatter.ofPattern(inPattern);
    DateTimeFormatter outFormat = DateTimeFormatter.ofPattern(outPattern);
    LocalDate date = LocalDate.parse(dateString, inFormat);
    return date.format(outFormat);
}
  • Related