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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With