Java 8从不包含所有字段的字符串解析ZonedDateTime

时间:2016-11-02 19:05:09

标签: java time

当我只在字符串模式中指定年份(可能还有其他几个时间字段)时,我希望将其他缺席字段设置为最低值。例如,在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: Text '2008' could not be parsed: Unable to obtain
    ZonedDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2008},ISO
        of type java.time.format.Parsed

如何使用Java 8时间API获得与使用旧API时相同的结果?

1 个答案:

答案 0 :(得分:2)

它有点冗长,但您必须在创建DateTimeFormatter时指定缺失字段的默认值:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(ChronoField.YEAR)
        .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
        .toFormatter()
        .withZone(ZoneOffset.UTC);

ZonedDateTime zonedDateTime = ZonedDateTime.parse("2008", fmt);

这包括ZoneId所需的ZonedDateTime