简体   繁体   English

如何在Java中将Gregorian Calendar转换为Unix Time?

[英]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 (ie a long). 我需要一个方法将GregorianCalendar对象转换为Unix时间(即很长)。 Also need a method to convert Unix Time (long) back to GregorianCalendar Object. 还需要一种方法将Unix Time(long)转换回GregorianCalendar对象。 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 链接到GregorianCalendar类 - > http://download.oracle.com/javase/1.4.2/docs/api/java/util/GregorianCalendar.html

Thanks. 谢谢。

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. 方法getTimeInMillis()setTimeInMillis(long)将允许您以毫秒为单位获取和设置时间,即unix时间乘以1000.您必须手动调整,因为unix时间不包括毫秒 - 仅秒。

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. 另外 :如果您在应用程序中使用了很多日期,特别是如果您要转换日期或使用多个时区,我强烈建议您使用JodaTime库。 It is very complete and quite a bit more natural to understand than the Calendar system that comes with Java. 它比Java附带的Calendar系统更完整,更自然。

我相信GregorianCalendar.getTimeInMillis()GregorianCalendar.SetTimeInMillis()可以让你以你想要的方式获取和设置长值。

查看setTimeInMillis和getTimeInMillis函数: http//download.oracle.com/javase/6/docs/api/java/util/Calendar.html#getTimeInMillis ()

Calendar.getTimeInMillis()应该是您正在寻找的。

tl;dr TL;博士

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. 但是,仅供参考,麻烦的旧日期时间类如java.util.Datejava.util.Calendarjava.text.SimpleDateFormat现在是遗留的 ,取而代之的是Java 8和Java 9中内置的java.time类。

So here is how to convert and use the modern classes instead for your problem. 所以这里是如何转换和使用现代类代替您的问题。

java.time java.time

Convert from the legacy class GregorianCalendar to the modern class ZonedDateTime . 从遗留类GregorianCalendar转换为现代类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 . 如果通过“Unix时间”你的意思是自1970年第一时刻的纪元参考以来在UTC,1970-01-01T00:00:00Z中的整秒数,则调用toEpochSecond

long secondsSinceEpoch = zdt.toEpochSecond() ;

If you meant a count of milliseconds since 1970 started in UTC, then extract an Instant . 如果你的意思是自1970年以UTC开始的毫秒数,那么提取一个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类表示UTC时间轴上的一个时刻,分辨率为纳秒 (最多九(9)位小数)。

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. ZonedDateTimeInstant都解析为纳秒。 So any microseconds or nanoseconds that may be present will be ignored as you count your whole seconds or milliseconds. 因此,当您计算整秒或毫秒时,将忽略可能存在的任何微秒或纳秒。


About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. 使用符合JDBC 4.2或更高版本的JDBC驱动程序 ,您可以直接与数据库交换java.time对象。 No need for strings nor java.sql.* classes. 不需要字符串也不需要java.sql。*类。

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM