Eli*_*456 2 java datetime simpledateformat datetimeformatter
我想比较 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);
Run Code Online (Sandbox Code Playgroud)
您可以使用 aDateTimeFormatterBuilder创建一个DateTimeFormatter可以解析具有“st”、“nd”、“rd”和“th”后缀以及小写 AMPM 的月份日期的 a 。
// 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);
Run Code Online (Sandbox Code Playgroud)
用法:
LocalDateTime datetime = LocalDateTime.parse("April 5th 2021 12:30pm", dateFormatter);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |