将 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:10:51  来源:igfitidea点击:

Converting java.time to Calendar

javajava-time

提问by Daniel C. Sobral

What is the simplest way of getting a Calendarobject from a java.time.Instantor java.time.ZonedDateTime?

Calendar从 ajava.time.Instant或获取对象的最简单方法是java.time.ZonedDateTime什么?

回答by Rohit Jain

Getting a Calendarinstant from ZonedDateTimeis 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 Calendarclass. Not a very deep discussion though.

如果您知道存在一种方法,那么获取Calendar瞬间ZonedDateTime是非常简单的GregorianCalendar#from(ZonedDateTime)。在Threeten-dev 邮件组中有一个讨论,关于为什么该方法不在Calendar课堂上。虽然不是很深入的讨论。

However, there is no direct way to convert from an Instantto Calendar. You've to have an intermediate state for that:

但是,没有直接的方法可以从 an 转换InstantCalendar。你必须有一个中间状态:

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 Instantmaps to Daterather than a Calendar. Similarly, a ZonedDateTimemaps 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))