旧版日期时间


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.utiljava.time 对象之间进行转换的方法:

  • Calendar.toInstant() converts the Calendar object to an Instant.
  • GregorianCalendar.toZonedDateTime() converts a GregorianCalendar instance to a ZonedDateTime.
  • GregorianCalendar.from(ZonedDateTime) creates a GregorianCalendar object using the default locale from a ZonedDateTime instance.
  • Date.from(Instant) creates a Date object from an Instant.
  • Date.toInstant() converts a Date object to an Instant.
  • TimeZone.toZoneId() converts a TimeZone object to a ZoneId.

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.FormatterString.format() 一起使用与 java.util 日期和时间类一起使用的基于格式的格式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值