Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String into java.time.ZonedDateTime

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?

like image 520
SSF Avatar asked Mar 05 '23 19:03

SSF


2 Answers

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>>)));
like image 112
mallikarjun Avatar answered Mar 11 '23 12:03

mallikarjun


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);
like image 24
SSF Avatar answered Mar 11 '23 12:03

SSF