created: 2022-07-24T14:59:24+08:00
updated: 2022-07-24T15:10:39+08:00
tags:
- DateTimeAPI
Legacy Date-Time Code
Interoperability with Legacy Code
JDK 8 版本中添加了几种允许在 java.util
和 java.time
对象之间进行转换的方法:
Calendar.toInstant()
converts theCalendar
object to anInstant
.GregorianCalendar.toZonedDateTime()
converts aGregorianCalendar
instance to aZonedDateTime
.GregorianCalendar.from(ZonedDateTime)
creates aGregorianCalendar
object using the default locale from aZonedDateTime
instance.Date.from(Instant)
creates aDate
object from anInstant
.Date.toInstant()
converts aDate
object to anInstant
.TimeZone.toZoneId()
converts aTimeZone
object to aZoneId
.
example1
Calendar now = Calendar.getInstance();
ZonedDateTime zdt = ZonedDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()));
example2
Instant inst = date.toInstant();
Date newDate = Date.from(inst);
example3
GregorianCalendar cal = ...;
TimeZone tz = cal.getTimeZone();
int tzoffset = cal.get(Calendar.ZONE_OFFSET);
ZonedDateTime zdt = cal.toZonedDateTime();
GregorianCalendar newCal = GregorianCalendar.from(zdt);
LocalDateTime ldt = zdt.toLocalDateTime();
LocalDate date = zdt.toLocalDate();
LocalTime time = zdt.toLocalTime();
Mapping Legacy Date and Time Functionality to the Date Time API
略
Date and Time Formatting
尽管 java.time.format.DateTimeFormatter
为格式化日期和时间值提供了强大的机制,但您也可以使用相同的模式直接将 java.time
基于时间的类与 java.util.Formatter
和 String.format()
一起使用与 java.util
日期和时间类一起使用的基于格式的格式。