4

I want to convert elements of an array list into ZonedDateTime object after parsing them. A string is shown below.

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

At the moment I use the DateTimeFormatter:

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

And try to use parse, to get the time:

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
SSF
  • 915
  • 5
  • 23
  • 47
  • 2
    I changed `YYYY` (week-based-year) to `yyyy` (year-of-era) and used `System.out.println(ZonedDateTime.parse("2017-02-12 06:59:00 +1300", dateTimeFormatter));` which printed `2017-02-12T06:59+13:00` – MadProgrammer Jul 19 '18 at 05:07
  • Your string contains an offset (+1300), not a time zone (like Pacific/Fakaofo), so it would really be more correct and also somehow simpler to parse it into an `OffsetDateTime` rather than a `ZonedDateTime`. – Ole V.V. Jul 19 '18 at 13:13

2 Answers2

5

In the DateTimeFormatter years should be small letters. 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. In your code the ZoneId instance will give you default ZoneId. It will fall back to LocalDateTime. If you want to specify the ZoneId use the following

this.actionTime =  ZonedDateTime.parse(actionTime, dateTimeFormatter.withZone(ZoneId.of(<<yourxoneid>>)));
Abra
  • 19,142
  • 7
  • 29
  • 41
mallikarjun
  • 1,862
  • 5
  • 23
  • 47
2

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);
Abra
  • 19,142
  • 7
  • 29
  • 41
SSF
  • 915
  • 5
  • 23
  • 47