Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert from Gregorian Calendar to Unix Time, in Java?

I am in need of a method to convert GregorianCalendar Object to Unix Time (i.e. a long). Also need a method to convert Unix Time (long) back to GregorianCalendar Object. Are there any methods out there that does this? If not, then how can I do it? Any help would be highly appreciated.

Link to GregorianCalendar Class --> http://download.oracle.com/javase/1.4.2/docs/api/java/util/GregorianCalendar.html

Thanks.

like image 666
androidNoob Avatar asked Oct 25 '10 20:10

androidNoob


People also ask

What is Unix time in Java?

Unix time (also known as POSIX time or epoch time), is a system for describing a point in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus the number of leap seconds that have taken place since then.

Is the Gregorian calendar still used in Java?

The java. util. GregorianCalendar class in Java is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.

What is the difference between Calendar and Gregorian calendar in Java?

The major difference between GregorianCalendar and Calendar classes are that the Calendar Class being an abstract class cannot be instantiated. So an object of the Calendar Class is initialized as: Calendar cal = Calendar. getInstance();


1 Answers

The methods getTimeInMillis() and setTimeInMillis(long) will let you get and set the time in milliseconds, which is the unix time multiplied by 1000. You will have to adjust manually since unix time does not include milliseconds - only seconds.

long unixTime = gregCal.getTimeInMillis() / 1000;
gregCal.setTimeInMillis(unixTime * 1000);

Aside: If you use dates a lot in your application, especially if you are converting dates or using multiple time zones, I would highly recommend using the JodaTime library. It is very complete and quite a bit more natural to understand than the Calendar system that comes with Java.

like image 146
Erick Robertson Avatar answered Oct 03 '22 01:10

Erick Robertson