将 java.time 转换为 Calendar
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28779179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting java.time to Calendar
提问by Daniel C. Sobral
What is the simplest way of getting a Calendar
object from a java.time.Instant
or java.time.ZonedDateTime
?
Calendar
从 ajava.time.Instant
或获取对象的最简单方法是java.time.ZonedDateTime
什么?
回答by Rohit Jain
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.
如果您知道存在一种方法,那么获取Calendar
瞬间ZonedDateTime
是非常简单的GregorianCalendar#from(ZonedDateTime)
。在Threeten-dev 邮件组中有一个讨论,关于为什么该方法不在Calendar
课堂上。虽然不是很深入的讨论。
However, there is no direct way to convert from an Instant
to Calendar
. You've to have an intermediate state for that:
但是,没有直接的方法可以从 an 转换Instant
为Calendar
。你必须有一个中间状态:
Instant instant = Instant.now();
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
Calendar cal1 = GregorianCalendar.from(zdt);
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
.
这可能是因为,从本 oracle 教程的表格中可以明显看出, aInstant
映射到Date
而不是Calendar
. 同样, aZonedDateTime
映射到 a Calendar
。
回答by Richard Barker
You need to get the TimeZone using the instant and then you can get a calendar.
您需要使用即时获取时区,然后才能获取日历。
Calendar myCalendar = GregorianCalendar.from(ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));
回答by Nils Breunese
How about GregorianCalendar.from(ZonedDateTime.ofInstant(instant, zoneId))
?
怎么样GregorianCalendar.from(ZonedDateTime.ofInstant(instant, zoneId))
?