将java.util.Date转换为java.time.LocalDate

本文翻译自:Convert java.util.Date to java.time.LocalDate

What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate ? java.util.Date对象转换为新的JDK 8 / JSR-310 java.time.LocalDate的最佳方法是什么?

Date input = new Date();
LocalDate date = ???

#1楼

参考:https://stackoom.com/question/1R82g/将java-util-Date转换为java-time-LocalDate


#2楼

Short answer 简短答案

Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Explanation 说明

Despite its name, java.util.Date represents an instant on the time-line, not a "date". 尽管其名称, java.util.Date表示时间轴上的一个瞬间,而不是“日期”。 The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC). 自1970-01-01T00:00Z(1970 GMT / UTC开始的午夜)以来,存储在对象中的实际数据是很long的毫秒数。

The equivalent class to java.util.Date in JSR-310 is Instant , thus there is a convenient method toInstant() to provide the conversion: JSR-310中与java.util.Date等效的类是Instant ,因此有一个方便的方法toInstant()提供转换:

Date input = new Date();
Instant instant = input.toInstant();

A java.util.Date instance has no concept of time-zone. 一个java.util.Date实例没有时区的概念。 This might seem strange if you call toString() on a java.util.Date , because the toString is relative to a time-zone. 如果在java.util.Date上调用toString() ,这似乎很奇怪,因为toString是相对于时区的。 However that method actually uses Java's default time-zone on the fly

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值