Getting java.time.format.DateTimeParseException: Text 'December 05, 2020 at 10:00:00 AM PDT' could not be parsed at index 17

132 Views Asked by At

I am trying to run the below code in IntelliJ IDE and getting the parsing exception whereas the code works on the online Java Compiler. Can somebody please help me understand what I am doing wrong?

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;


public class MyClass {
    public static void main(String args[]) {
      String slot = "December 05, 2020 at 10:00:00 AM PDT";
      String locale = "en-US";
      String timezone = "America/Los_Angeles";
      long epoch = convertDateToLong(slot, locale, timezone);
      System.out.println(epoch);
    }
    
    private static long convertDateToLong (String dateTimeString, String locale, String timezone) {
        ZoneId zoneId = ZoneId.of(timezone);
        String offsetId = ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(timezone)).getOffset().toString();
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(zoneId).withLocale(Locale.forLanguageTag(locale));
        LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, formatter);
        long epoch = localDateTime.toEpochSecond(ZoneOffset.of(offsetId));
        return epoch * 1000;
    }
}

enter image description here

0

There are 0 best solutions below