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

帅比萌擦擦* 提交于 2019-12-08 14:56:42

问题


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.


回答1:


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.




回答2:


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




回答3:


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




回答4:


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




回答5:


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?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.



来源:https://stackoverflow.com/questions/4018488/how-can-i-convert-from-gregorian-calendar-to-unix-time-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!