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?

2
  • 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 Commented Jul 19, 2018 at 5:07
  • 1
    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. Commented Jul 19, 2018 at 13:13

2 Answers 2

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>>)));
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.