Converting java.time to Calendar

房东的猫 提交于 2019-12-21 07:21:29

问题


What is the simplest way of getting a Calendar object from a java.time.Instant or java.time.ZonedDateTime?


回答1:


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.

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);

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.




回答2:


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()));



回答3:


How about GregorianCalendar.from(ZonedDateTime.ofInstant(instant, zoneId))?



来源:https://stackoverflow.com/questions/28779179/converting-java-time-to-calendar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!