簡體   English   中英

將字符串轉換為 java.time.ZonedDateTime

[英]Convert String into java.time.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做到這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>>)));

我設法使用以下方法解決了這個問題:

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