gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:14:56 25 4
gpt4 key购买 nike

当我在字符串模式中仅指定年份(可能还有其他几个时间字段)时,我希望将其他不存在的字段设置为最低值。例如,在 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);

异常(exception):

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 time API 获得与使用旧版 API 相同的结果?

最佳答案

这有点冗长,但您必须在创建 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 所必需的.

关于Java 8从不包含所有字段的字符串中解析ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40387855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com