Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I believe that GregorianCalendar.getTimeInMillis() and GregorianCalendar.SetTimeInMillis() will let you get and set long values the way you want.

Check out the setTimeInMillis and getTimeInMillis functions: http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html#getTimeInMillis()

Calendar.getTimeInMillis() should be what you're looking for.

tl;dr

myGregCal.toZonedDateTime().toEpochSecond()                     // Convert from troublesome legacy `GregorianCalendar` to modern `ZonedDateTime`.

And going the other direction…

GregorianCalendar.from(                                         // Convert from modern `ZonedDateTime` to troublesome legacy class `GregorianCalendar`.
    Instant.ofEpochSecond( yourCountOfWholeSecondsSinceEpoch )  // Moment in UTC.
        .atZone(                                                // Apply `ZoneId` to `Instant` to produce a `ZonedDateTime` object.
            ZoneId.of( "Africa/Tunis" ) 
        )
)                                                              

Avoid legacy date-time classes

The other Answers are correct and short. But, FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9.

So here is how to convert and use the modern classes instead for your problem.

java.time

Convert from the legacy class GregorianCalendar to the modern class ZonedDateTime. Call new methods added to the old classes.

ZonedDateTime zdt = myGregCal.toZonedDateTime() ;

And going the other direction…

GregorianCalendar myGregCal = GregorianCalendar.from( zdt ) ;

If by “Unix time” you meant a count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z, then call toEpochSecond.

long secondsSinceEpoch = zdt.toEpochSecond() ;

If you meant a count of milliseconds since 1970 started in UTC, then extract an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now ask for the count of milliseconds.

long millisecondsSinceEpoch = instant.toEpochMill() ;

Keep in mind that asking for either whole seconds or milliseconds may involve data loss. The ZonedDateTime and Instant both resolve to nanoseconds. So any microseconds or nanoseconds that may be present will be ignored as you count your whole seconds or milliseconds.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top