Convert date with ordinal numbers (11th, 22nd, etc.)

前端 未结 3 1585
闹比i
闹比i 2021-01-14 09:15

How to convert a date having the following format

September 22nd 2015, 10:39:42 am

to

09/22/2015 10:39:42

3条回答
  •  暖寄归人
    2021-01-14 09:47

    Here a shorter Java-8-only solution without an external library:

    DateTimeFormatter formatter = 
      DateTimeFormatter.ofPattern(
        "MMMM d['st']['nd']['rd']['th'] yyyy, hh:mm:ss a", Locale.ENGLISH);
    formatter = 
      new DateTimeFormatterBuilder().parseCaseInsensitive().append(formatter).toFormatter();
    LocalDateTime dateTime = 
      formatter.parse("September 22nd 2015, 10:39:42 am", LocalDateTime::from);
    String text = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss").format(dateTime);
    System.out.println(text); // 09/22/2015 10:39:42
    

    There is only one caveat: The suggested parser might also accept funny inputs like "...22ndst..." etc. but I think this can be neglected here.

提交回复
热议问题