Creating a GregorianCalendar instance from milliseconds

Amir Rachum picture Amir Rachum · Dec 15, 2010 · Viewed 49k times · Source

I have a certain time in milliseconds (in a Timestamp object) and I want to use it to create a GregorianCalendar object. How can I do that?

EDIT: How do I do the reverse?

Answer

Michael Konietzka picture Michael Konietzka · Dec 15, 2010

Just get an instance of GregorianCalendar and setTime with your java.sql.Timestamp timestamp:

Calendar cal=GregorianCalendar.getInstance();
cal.setTime(timestamp);

Edit: As peterh pointed out, GregorianCalendar.getInstance() will not provide a GregorianCalendar by default, because it is inherited fromCalendar.getInstance(), which can provide for example a BuddhistCalendar on some installations. To be sure to use a GregorianCalender use new GregorianCalendar() instead.