java8新旧时间转化

来源:互联网 发布:淘宝有2元东西包邮的吗 编辑:程序博客网 时间:2024/06/05 04:04

为了能够兼容老的Date Time对象,新API提供了几个工具方法,让我们可以在新老日期对象之间进行转换。
这里写图片描述
这里写图片描述

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);    }}
0 0
原创粉丝点击