Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting java.time to Calendar

Tags:

java

java-time

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

like image 767
Daniel C. Sobral Avatar asked Feb 28 '15 07:02

Daniel C. Sobral


People also ask

How do I convert a string to a Calendar instance?

You can use following code to convert string date to calender format. String stringDate="23-Aug-10"; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Date date = formatter. parse(stringDate); Calendar calender = Calendar. getInstance(); calender.

Can we format Calendar in Java?

You can format the calender date object when you want to display and keep that as a string.

How do you convert a Calendar to date and vice versa in Java?

Well, you can use the Calendar. setTime() and Calendar. getTime() method to convert the Calendar to Date and vice-versa.


2 Answers

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())); 
like image 43
Richard Barker Avatar answered Sep 22 '22 16:09

Richard Barker


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.

like image 168
Rohit Jain Avatar answered Sep 22 '22 16:09

Rohit Jain