java时间

jdk8以前

Date 保存了时间戳,可以确定一个时刻,无时区信息
Calendar 保存了时间戳和时区,可以确定一个时刻,另外有一些方便的操作
TimeZone 时区
SimpleDateFormat 格式化/解析Date(字符串带时区才能确定一个时刻,才是有意义的;不带时区解析出来的Date,其实是使用了默认时区)

jkd8新增

Instant 时间戳,时刻
LocalDateTime 不带时区,无法确定一个时刻
ZonedDateTime 带时区和时间戳,可以确定一个时刻
ZoneId 时区
DateTimeFormatter 格式化/解析LocalDateTime、ZonedDateTime

相互转换

Date对应Instant

Instant ins1 = new Date().toInstant();
Date date = new Date(Instant.now().toEpochMilli())

Calendar 对应ZonedDateTime

// Calendar -> Instant -> ZonedDateTime:
Calendar calendar = Calendar.getInstance();
Instant ins2 = calendar.toInstant();
ZonedDateTime zdt = ins2.atZone(calendar.getTimeZone().toZoneId());

// ZonedDateTime -> Instant -> Calendar 
ZonedDateTime zdt = ZonedDateTime.now();
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeZone(TimeZone.getTimeZone(zdt.getZone().getId()));
calendar.setTimeInMillis(zdt.toInstant().toEpochMilli());

LocalDateTime转ZonedDateTime,需要带上时区(注意有夏令时的影响,会自动调整结果)

// 进入夏令时,凌晨两点往后拨一小时,因此2点31是不存在的,自动往后加一小时变成"2023-03-12T03:31-04:00[America/New_York]"
 LocalDateTime localDateTime1 = LocalDateTime.of(2023, 3, 12, 2, 31, 00);
 ZonedDateTime zonedDateTime1 = ZonedDateTime.of(localDateTime1, ZoneId.of("America/New_York"));

// 正常的处于夏令时的某一天"2023-03-12T04:31-04:00[America/New_York]"
LocalDateTime localDateTime2 = LocalDateTime.of(2023, 3, 12, 4, 31, 00);
ZonedDateTime zonedDateTime2 = ZonedDateTime.of(localDateTime2, ZoneId.of("America/New_York"));


// 正常的处于冬令时的某一天"2022-12-12T04:31-05:00[America/New_York]"
LocalDateTime localDateTime3 = LocalDateTime.of(2022, 12, 12, 4, 31, 00);
ZonedDateTime zonedDateTime3 = ZonedDateTime.of(localDateTime2, ZoneId.of("America/New_York"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值