【发布时间】:2015-10-22 11:27:20
【问题描述】:
我必须将日期字符串(例如“2015 年 10 月”)解析为日期。
所以问题是:如何解析MMMM yyyy 格式的日期?如果新的 Date 对象是给定月份的第一个月,则可以。
我试过了:
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM yyyy").toFormatter();
TemporalAccessor ta = formatter.parse(node.textValue());
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
但由于缺少这一天,它不起作用。
【问题讨论】:
-
@GaëlJ 请不要教年轻人使用早已过时且臭名昭著的麻烦
SimpleDateFormat类。尤其是当他们已经在使用 java.time(现代 Java 日期和时间 API)时,就像在这个问题中一样。好多了。