'Need to convert file name based on date [closed]

We have a requirement to where the input file will be KYB_FX_SPOT_AUTO.20220327 where KYB_FX_SPOT_AUTO. would be a constant and 20220327 is dynamic part which is date in format yyyyddMM, we need to assign a variable then a name AUTO_FXUPLOAD_APR2022.CSV , where other than APR2022 , rest other part is constant. Please help me with just a piece of code to convert 20220327 name to APR2022.Please note the month in source is march and APR in target which means month has to increment by one and accordingly the year might increase in case of December month. Thanks.



Solution 1:[1]

If you are using Java 8 or any later version, you can use classes from java.time.

You can convert a date String of the pattern "uuuuMMdd" to one formatted as "MMMuuuu" like this:

public static void main(String[] args) {
    // your example String date
    String date = "20220327";
    // prepare a parser for the pattern of your input
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuuMMdd");
    // parse the String to a LocalDate using the parser
    LocalDate localDate = LocalDate.parse(date, parser);
    // prepare a formatter for your desired output
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMuuuu", Locale.ENGLISH);
    // prepare some result message using the parser and the formatter…
    String resMsg = String.format("%s ———> %s", 
                                localDate.format(parser),
                                localDate.format(formatter).toUpperCase());
    // … then print the message
    System.out.println(resMsg);
}

The output of this is

20220327 ———> MAR2022

To create your desired result considering year changes when adding or subtracting a month, maybe use a YearMonth. Create ony by getting the year and month of the LocalDate and safely add one month to it.

Here's one option:

// extract the year month and add 1
YearMonth yearMonth = YearMonth.from(localDate).plusMonths(1);
// print the result
System.out.println("+ 1 month ==> " + yearMonth.format(formatter).toUpperCase());

Appending the above lines to the example main would add another line to the output:

+ 1 month ==> APR2022

Solution 2:[2]

What you are looking for is date formatting. You can use Date formats to parse the date, then output it in a different format.

The relevant classes are Date and SimpleDateFormat. For the calculation part, use Calendar.

// parse the date
String input = "20220327";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = inputFormat.parse(input);

// For the calculation part, refer to the javadoc of Calendar
// ...

// output in new format
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMyyyy")
String output = outputFormat.format(myDate);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kutschkem