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/

相关文章:

php - 计算用户连接到站点的时间

java - 如何使用 java.sql.Time 构造函数从长值创建时间

java - 将 org.joda.time.Period 转换为 java.time.Period

java - 初级 Java - 使用 substring() 将长字符串分成单独的行

java - 如何编写一个没有获得焦点的Java应用程序?

java - 使用部署在 Oracle Weblogic 服务器上的 Java 代码时,数据泵目录中的 chmod 命令第二次不起作用

java - 将 LocalDateTime 转换为 UTC 中的 LocalDateTime

java - 扫描蓝牙设备

time - 算法时间复杂度分析

Java 8 Date 等效于 Joda 的 DateTimeFormatterBuilder,具有多种解析器格式?