java8中的时间处理7 - 向前兼容(新老类转换)
我们不太可能使用jdk8以后就把原来的代码都改成新api。所以新旧日期类会共存一段时间。
这篇提供他们之间的转换。
public static void main(String[] args) {
//Date 转 Instant
Instant timestamp = new Date().toInstant();
//其他类都有ofInstant方法用来转换Instant
LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("CTT")));
System.out.println(date);
//Calendar 转 Instant
Instant time = Calendar.getInstance().toInstant();
System.out.println(time);
//TimeZone 转 ZoneId
ZoneId defaultZone = TimeZone.getDefault().toZoneId();
System.out.println(defaultZone);
//Calendar 转 ZonedDateTime
ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
System.out.println(gregorianCalendarDateTime);
//兼容API
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);
}