2

我想比较 WebElements 日期以验证排序是否正确。但是,日期的值例如如下:“April 5th 2021 12:30pm”、“October 22nd 09:18am”、“February 1st 11:36pm”、

我已经尝试了下面的代码,但它返回 1970 作为日期,并且在日期为 2 位的情况下返回错误:


DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d yyyy HH:mma", Locale.US);
LocalDate date = LocalDate.parse(dt, dateFormatter);

// or

Date sdf = new SimpleDateFormat("MMMM d u hh:mma").parse(dt);



4

2 回答 2

4

您可以使用 aDateTimeFormatterBuilder创建一个DateTimeFormatter可以解析具有“st”、“nd”、“rd”和“th”后缀以及小写 AMPM 的日期的月份。

// first create a map containing mapping the days of month to the suffixes
HashMap<Long, String> map = new HashMap<>();
for (long i = 1 ; i <= 31 ; i++) {
  if (i == 1 || i == 21 || i == 31) {
    map.put(i, i + "st");
  } else if (i == 2 || i == 22){
    map.put(i, i + "nd");
  } else if (i == 3 || i == 23) {
    map.put(i, i + "rd");
  } else {
    map.put(i, i + "th");
  }
}

DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
    .appendPattern("MMMM ")
    .appendText(ChronoField.DAY_OF_MONTH, map) // here we use the map
    .appendPattern(" yyyy HH:mm")
    .appendText(ChronoField.AMPM_OF_DAY, Map.of(0L, "am", 1L, "pm")) // here we handle the lowercase AM PM
    .toFormatter(Locale.US);

用法:

LocalDateTime datetime = LocalDateTime.parse("April 5th 2021 12:30pm", dateFormatter);
于 2021-04-20T05:18:15.813 回答
1

格式模式d只接受一个数字,不接受st、nd、rd和th。

将可选部分与[和一起使用]。此外,a应该与 一起使用hh,而不是HH

好的。似乎Locale.US只接受“AM”和“PM”,而Locale.UK只接受“am”和“pm”。

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d['st']['nd']['rd']['th'] yyyy hh:mma", Locale.UK);
LocalDate date = LocalDate.parse(dt, dateFormatter);

或者

DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("MMMM d['st']['nd']['rd']['th'] yyyy hh:mma")
        .toFormatter(Locale.US);
LocalDate date = LocalDate.parse(dt, dateFormatter);
于 2021-04-20T05:12:08.333 回答