【发布时间】:2017-03-16 05:34:28
【问题描述】:
当我在字符串模式中仅指定年份(可能还有其他几个时间字段)时,我希望将其他不存在的字段设置为它们的最低值。例如,在 Java 8 之前,我的代码看起来像
String source = "2015";
String pattern = "yyyy";
DateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
String newf = sdfGMT2.format(date);
System.out.println(newf);
返回给我2015.01.01 00:00:00 GMT
然而,java.time 格式化程序返回一个TemporalAccessor;下面的代码抛出异常
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("YYYY");
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2008", fmt);
例外:
java.time.format.DateTimeParseException:无法解析文本“2008”:无法获取 来自 TemporalAccessor 的 ZonedDateTime:{WeekBasedYear[WeekFields[SUNDAY,1]]=2008},ISO java.time.format.Parsed 类型的如何使用 Java 8 time API 获得与使用旧 API 相同的结果?
【问题讨论】: