简体   繁体   中英

How to convert string into valid date format if I provide month and days as optional

I want to convert my string into valid date format even months and days are optional

For Example, I have the following string like below

String date1 = "20-12-2021"
String date2 = "12-2021" i.e without day
String date3 = "2021" i.e without day & month
String date4 = "21" i.e without day, month & just last two digits of the year

I want to convert all the above strings format into the valid date with 'yyyy-mm-dd' format as below,

For date1, Date should be "2021-12-20" 
For date2, Date should be "2021-12-01"
For date3, Date should be "2021-01-01" 
For date4, Date should be "2021-01-01"

Could you please help me with this? Any info will be really helpful. I can't define single string formatted for parser since the string format is unpredictable in my scenario.

You can use DateTimeFormatterBuilder with multiple patterns and default values of missing parts (month and day):

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("[dd-MM-uuuu]")
        .appendPattern("[MM-uuuu]")
        .appendPattern("[uuuu]")
        .appendPattern("[uu]")
        .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
        .toFormatter();

Outputs

2021-12-20
2021-12-01
2021-01-01
2021-01-01

A whacky yet working solution in your special case would be the following:

public class DateParser {
  private static String defaultDate = "01-01-2000";
  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
  
  public static LocalDate parseDate(String date) {
    String fullDate = defaultDate.substring(0, defaultDate.length() - date.length()) + date;
    return LocalDate.parse(fullDate, formatter);
  }

}

Basically, use a default full date, eg 01-01-2000 , and then combine it with the input date. Then, use the formatter dd-MM-yyyy to parse the date. One of the advantages is that it reuses the same formatter, hence is very efficient. However, you may need to add some checks and exception handling.

To test it:

public static void main(String[] args) {
  List.of(
      "20-12-2021",
      "12-2021",
      "2021",
      "21"
  ).forEach(date -> System.out.println(parseDate(date)));
}

Output:

2021-12-20
2021-12-01
2021-01-01
2021-01-01

(I must admit @YCF_L solution is more elegant though)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM