如何在 Java 中从公历转换为 Unix 时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4018488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert from Gregorian Calendar to Unix Time, in Java?
提问by androidNoob
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.
我需要一种将 GregorianCalendar 对象转换为 Unix 时间(即 long)的方法。还需要一种将 Unix 时间(长)转换回 GregorianCalendar 对象的方法。是否有任何方法可以做到这一点?如果没有,那我该怎么做?任何帮助将不胜感激。
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.
谢谢。
回答by Erick Robertson
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 JodaTimelibrary. It is very complete and quite a bit more natural to understand than the Calendar system that comes with Java.
旁白:如果您在应用程序中经常使用日期,尤其是在转换日期或使用多个时区时,我强烈建议您使用JodaTime库。它非常完整,比 Java 附带的日历系统更易于理解。
回答by MattC
I believe that GregorianCalendar.getTimeInMillis()and GregorianCalendar.SetTimeInMillis()will let you get and set long values the way you want.
我相信GregorianCalendar.getTimeInMillis()和GregorianCalendar.SetTimeInMillis()会让你以你想要的方式获取和设置长值。
回答by Riley Lark
Check out the setTimeInMillis and getTimeInMillis functions: http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html#getTimeInMillis()
查看 setTimeInMillis 和 getTimeInMillis 函数:http: //download.oracle.com/javase/6/docs/api/java/util/Calendar.html#getTimeInMillis()
回答by Nick
Calendar.getTimeInMillis() should be what you're looking for.
Calendar.getTimeInMillis() 应该是你要找的。
回答by Basil Bourque
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.timeclasses built into Java 8 & Java 9.
其他答案正确且简短。但是,仅供参考,麻烦的旧日期,时间类,如java.util.Date
,java.util.Calendar
和java.text.SimpleDateFormat
现在的遗产,由取代java.time内置到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.
从遗留类GregorianCalendar
转换为现代类ZonedDateTime
。调用添加到旧类的新方法。
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 referenceof first moment of 1970 in UTC, 1970-01-01T00:00:00Z, then call toEpochSecond
.
如果“Unix 时间”是指自UTC 中 1970 年第一时刻的纪元参考以来的整秒计数,即 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
. The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).
如果您的意思是从 1970 年以 UTC 开始计算毫秒数,那么提取一个Instant
. 该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 millisecondsmay involve data loss. The ZonedDateTime
and Instant
both resolve to nanoseconds. So any microsecondsor nanoseconds that may be present will be ignored as you count your whole seconds or milliseconds.
请记住,请求整秒或毫秒可能会导致数据丢失。在ZonedDateTime
与Instant
两决心纳秒。因此,当您计算整个秒或毫秒时,可能存在的任何微秒或纳秒都将被忽略。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Using a JDBC drivercompliant with JDBC 4.2or later, you may exchange java.timeobjects directly with your database. No need for strings nor java.sql.* classes.
使用符合JDBC 4.2或更高版本的JDBC 驱动程序,您可以直接与您的数据库交换java.time对象。不需要字符串或 java.sql.* 类。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- 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 6and 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 ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 Android,ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject 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.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。