将java.time转换为Calendar [英] Converting java.time to Calendar
问题描述
从java.time.Instant
或java.time.ZonedDateTime
获取Calendar
对象的最简单方法是什么?
What is the simplest way of getting a Calendar
object from a java.time.Instant
or java.time.ZonedDateTime
?
推荐答案
如果您知道存在 Threeten-dev邮件组,说明为什么该方法不在Calendar
类中.不过,讨论不是很深入.
Getting a Calendar
instant from ZonedDateTime
is pretty straight-forward, provided you know that there exists a GregorianCalendar#from(ZonedDateTime)
method. There was a discussion in Threeten-dev mail group, about why that method is not in Calendar
class. Not a very deep discussion though.
但是,没有直接的方法可以将Instant
转换为Calendar
.您必须为此设置一个中间状态:
However, there is no direct way to convert from an Instant
to Calendar
. You've to have an intermediate state for that:
Instant instant = Instant.now();
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
Calendar cal1 = GregorianCalendar.from(zdt);
这可能是因为,从此oracle教程的表中可以明显看出,Instant
映射到Date
而不是Calendar
.同样,ZonedDateTime
映射到Calendar
.
This is probably because, as evident from the table on this oracle tutorial, an Instant
maps to Date
rather than a Calendar
. Similarly, a ZonedDateTime
maps to a Calendar
.
这篇关于将java.time转换为Calendar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!