java - 将字符串转换为 java.time.ZonedDateTime

标签 java time java-time datetime-parsing zoneddatetime

我想在解析后将数组列表的元素转换为 ZonedDateTime 对象。下面显示了一个字符串。

"2017-02-12 06:59:00 +1300"

目前我使用DateTimeFormatter:

DateTimeFormatter dateTimeFormatter =
  DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss ZZ");

并尝试使用parse,获取时间:

this.actionTime = dateTimeFormatter.parse(actionTime, ZonedDateTime::from);

见下面的方法:

public DateCalculatorTest(String actionTime, int expectedDayOfWeek) {
    DateTimeFormatter dateTimeFormatter = 
      DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss ZZ");
    DateTimeFormatter localTimeFormatter = 
      DateTimeFormatter.ofPattern("YYYY-MM-dd");
    this.actionTime = dateTimeFormatter.parse(actionTime, ZonedDateTime::from);
    this.expectedDayOfWeek = expectedDayOfWeek;
}

但是,我无法解析字符串。我收到以下错误:

Text '2017-02-12 06:59:00 +1300' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2017, DayOfMonth=12, MonthOfYear=2, OffsetSeconds=46800},ISO resolved to 06:59 of type java.time.format.Parsed

有没有办法用 java.time 做到这一点?

最佳答案

DateTimeFormatter 年应该是小写字母。替换

 YYYY-MM-dd HH:mm:ss ZZ

yyyy-MM-dd HH:mm:ss ZZ

而且不需要两个ZZ,一个就够了。在您的代码中,ZoneId 实例将为您提供默认的 ZoneId。它将返回到 LocalDateTime。如果你想指定 ZoneId 使用下面的

this.actionTime =  ZonedDateTime.parse(actionTime, dateTimeFormatter.withZone(ZoneId.of(<<yourxoneid>>)));

关于java - 将字符串转换为 java.time.ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51414625/

相关文章:

java - 动态方法调度如何在 Java 中工作

java - Selenium -- 在浏览 Web 应用程序时,如何处理驱动程序当前 url 未快速更新的情况

实时时间到达时的 JavaScript 23 :00

swift 中的 java.util.enumeration 等价物

javascript - Jquery - 自动将当年月份添加到下拉列表

c - 我可以使用 C 中的什么函数来单独获取与时间分开的日期?

java-8 - 如何使用 Java8 Date API 将 "December 15, 2009"解析为 Date?

java.time.format.DateTimeParseException : Text could not be parsed at index 21

java - 如何在 Java 中将当前日期加一个月?

java - Selenium 网络驱动程序 : getText() returning empty String for h2 tag