欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 8 time api test

程序员文章站 2024-01-11 19:03:52
...
public class ParseUtcDateTimeStringTest {

     @Test
     public void testUtcStringToDate() {
        // "Z" at the end of the date time string is for UTC
        String utcDateStr = "2017-08-28T02:03:41.080Z";
        System.out.println("====== testUtcStringToDate: " + utcDateStr);

        // Parse the utc datetime string to java.time.Instant - defaults formatter to DateTimeFormatter.ISO_INSTANT.
        Instant instant = Instant.parse(utcDateStr);
        System.out.println("Parsed instant in UTC: " + instant);

        // single quote around 'T'
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

        // convert to LocalDateTime with default time zone
        ZoneId defaultZone = ZoneOffset.systemDefault();
        System.out.println("defaultZone: " + defaultZone);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of(defaultZone.getId()));
        System.out.println("Converted localDateTime=" + localDateTime);

        // convert to ZonedDateTime - you cannot format an Instant, have to convert it to a formattable date time
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of(defaultZone.getId()));
        System.out.println("Formatted zonedDateTime=" + formatter.format(zonedDateTime));

        // get ZoneOffset and then ZoneRules
        ZoneOffset zoneOffset = zonedDateTime.getOffset();
        System.out.println("zoneOffset: " + zonedDateTime.getOffset());
        ZoneRules zoneRules = ZoneRules.of(zoneOffset);
        System.out.println("zoneRuels: " + zoneRules);

        // ZoneRules tells if it's daylight savings time...
        if (zoneRules.isDaylightSavings(instant)) {
            System.out.println("Auckland summer has daylight saving time, which is 13 hours ahead of UTC");
            Assert.assertEquals("2017-08-28T15:03:41.080", formatter.format(zonedDateTime));
        } else {
            System.out.println("Auckland has winter time 12 hours ahead of UTC");
            Assert.assertEquals("2017-08-28T14:03:41.080", formatter.format(zonedDateTime));
        }
    }
}