2022-10-21

Issue with parsing date time using ZonedDateTime and DateTimeFormatter

I am having two different results from these two blocks even though the input date/time to parse is the same

public class DateTimeFormatterUtilsTest 
{
    private static final String ISO_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";;
    private static final String ISO_DATETIME_TO_PARSE = "2007-12-03T10:15:30.000Z";
    private static final long TARGET_EPOCH_TIME = 1196676930000L;

    @Test
    public void testDateTimeFormatterUtils()  
    {
        ZoneId targetZoneid = TimeUtils.getZoneId(TIMEZONE.PST);    
        
        DateTimeFormatter formatter =  DateTimeFormatter.ISO_INSTANT.withZone(targetZoneid);
        long epochTime = parseDateTime(ISO_DATETIME_TO_PARSE, formatter);       
        assertTrue(epochTime == TARGET_EPOCH_TIME);
        
        
        // specify custom pattern       
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern(ISO_DATETIME_PATTERN).withZone(targetZoneid);
        epochTime = parseDateTime(ISO_DATETIME_TO_PARSE, formatter1);
        assertTrue(epochTime == TARGET_EPOCH_TIME);

    }
    
    public long parseDateTime(final String dateTimeString, DateTimeFormatter formatter)
    {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter);
        System.out.println("parsed zoned date time" + zonedDateTime);
        
        Instant instant = zonedDateTime.toInstant();
        long epochTime = instant.toEpochMilli();
        System.out.println("Epoch time for" + ISO_DATETIME_TO_PARSE + "is " + epochTime);
        return epochTime;
    }   
}

When I am using DateTimeFormatter.ISO_INSTANT I get the correct epoch time which is 1196676930000, however, when I am usin the .ofPattern method to create the DateTimeFormatter I am getting 1196705730000. Not sure why?

As you can see, the difference is 28 800 000 milliseconds or exactly 8 hours.



No comments:

Post a Comment