datetime—在java中设置日期字符串的格式

d8tt03nd  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(360)

这个问题在这里已经有答案了

您如何将一个月的某一天格式化为“11”、“21”或“23”(顺序指示符)(22个答案)
无法将一位数的小时和小写的am pm解析为java 8 localtime(6个答案)
在java中解析格式“2010年1月10日”的日期(带顺序指示器,st | nd | rd | th)(4个答案)
5天前关门了。
我想比较webelements的日期来验证排序是否正确。但是,日期的值如下所示:“2021年4月5日12:30pm”、“2018年10月22日09:18am”、“2015年2月1日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);
4si2a6ki

4si2a6ki1#

你可以使用 DateTimeFormatterBuilder 创建 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);
qco9c6ql

qco9c6ql2#

格式模式 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);

相关问题