简体   繁体   English

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

[英]Convert String into java.time.ZonedDateTime

I want to convert elements of an array list into ZonedDateTime object after parsing them.我想在解析数组列表的元素后将它们转换为ZonedDateTime对象。 A string is shown below.下面显示了一个字符串。

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

At the moment I use the DateTimeFormatter :目前我使用DateTimeFormatter

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

And try to use parse , to get the time:并尝试使用parse来获取时间:

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

See below method:看下面的方法:

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;
}

However, I am not able to parse the string.但是,我无法解析字符串。 I get the following error:我收到以下错误:

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

Is there a way to do this with java.time ?有没有办法用java.time做到这java.time

In the DateTimeFormatter years should be small letters.DateTimeFormatter年份应该是小写字母。 Replace代替

 YYYY-MM-dd HH:mm:ss ZZ

with

yyyy-MM-dd HH:mm:ss ZZ

And you don't require two ZZ, single is enough.而且你不需要两个ZZ,一个就够了。 In your code the ZoneId instance will give you default ZoneId .在您的代码中, ZoneId实例将为您提供默认ZoneId It will fall back to LocalDateTime .它将回退到LocalDateTime If you want to specify the ZoneId use the following如果要指定ZoneId使用以下命令

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

I managed to fix this using the following:我设法使用以下方法解决了这个问题:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss ZZ");
DateTimeFormatter localTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
this.symbol = symbol;
this.actionTime = ZonedDateTime.parse(actionTime, dateTimeFormatter);
this.actionDate = LocalDate.parse(expectedResult, localTimeFormatter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM