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

5

15

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.

Stapleton answered 25/10, 2010 at 20:17 Comment(0)
S
32

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.

Silsby answered 25/10, 2010 at 20:23 Comment(2)
The time method in Unix C programming returns a whole number of seconds. It always has. There is another method utime which uses a struct with two longs: one for seconds and one for microseconds.Silsby
Thanks. A setTimeInMillis was about the last I would have looked for. Because in Java 1.0 they had the great idea of non-mutable-instances (String, Date, Integer, Long etc. pp) and would not have expected that in 1.1 they given up on the best idea the java designer ever had.Provide
E
1

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

Entozoon answered 25/10, 2010 at 20:21 Comment(0)
Z
1

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

Zion answered 25/10, 2010 at 20:21 Comment(0)
L
0

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

Lavonlavona answered 25/10, 2010 at 20:22 Comment(0)
A
0

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.

Aplite answered 15/2, 2018 at 7:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.