Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a GregorianCalendar instance from milliseconds

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?

like image 894
Amir Rachum Avatar asked Dec 15 '10 13:12

Amir Rachum


People also ask

What is Gregorian calendar in Java?

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.

What is the return type for the getGregorianChange () method?

getGregorianChange() is an inbuilt method in Java which returns the Gregorian Calendar change date which is the change from Julian Calendar dates to Gregorian Calendar dates.

What is the use of calendar getInstance () in Java?

Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.


2 Answers

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.

like image 71
Michael Konietzka Avatar answered Sep 20 '22 21:09

Michael Konietzka


To get a GregorianCalendar object and not a Calendar object. Like Michael's answer provides, you can also do the following:

long timestamp = 1234567890; GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(timestamp); 

This assumes a UTC epoch timestamp.

like image 20
haaduken Avatar answered Sep 20 '22 21:09

haaduken