Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

Converting java.time to Calendar

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

Upvotes: 34

Views: 28606

Answers (3)

Nils Breunese
Nils Breunese

Reputation: 1179

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

Upvotes: 1

Batman
Batman

Reputation: 702

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

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213243

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.

Upvotes: 44

Related Questions