java8新旧时间转化

为了能够兼容老的Date Time对象,新API提供了几个工具方法,让我们可以在新老日期对象之间进行转换。
java8新旧时间转化_第1张图片
java8新旧时间转化_第2张图片

public class DateAPILegacySupport {

    public static void main(String[] args) {

        // Date to Instant
        Instant timestamp = new Date().toInstant();
        // Now we can convert Instant to LocalDateTime or other similar classes
        LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
        System.out.println("Date = " + date);

        // Calendar to Instant
        Instant time = Calendar.getInstance().toInstant();
        System.out.println(time);
        // TimeZone to ZoneId
        ZoneId defaultZone = TimeZone.getDefault().toZoneId();
        System.out.println(defaultZone);

        // ZonedDateTime from specific Calendar
        ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
        System.out.println(gregorianCalendarDateTime);

        // Date API to Legacy classes
        Date dt = Date.from(Instant.now());
        System.out.println(dt);

        TimeZone tz = TimeZone.getTimeZone(defaultZone);
        System.out.println(tz);

        GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
        System.out.println(gc);
    }
}

你可能感兴趣的:(Java基础)