Java:来自 unix 时间戳的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3371326/
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
Java: Date from unix timestamp
提问by RYN
I need to convert a unix timestamp to a date object.
I tried this:
我需要将 unix 时间戳转换为日期对象。
我试过这个:
java.util.Date time = new java.util.Date(timeStamp);
Timestamp value is: 1280512800
时间戳值为: 1280512800
The Date should be "2010/07/30 - 22:30:00" (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970
.
日期应该是“2010/07/30 - 22:30:00”(因为我是通过 PHP 得到的)但我得到Thu Jan 15 23:11:56 IRST 1970
.
How should it be done?
应该怎么做?
采纳答案by Pablo Santa Cruz
For 1280512800
, multiply by 1000, since java is expecting milliseconds:
对于1280512800
,乘以 1000,因为 java 需要毫秒:
java.util.Date time=new java.util.Date((long)timeStamp*1000);
If you already had milliseconds, then just new java.util.Date((long)timeStamp);
如果你已经有毫秒,那么就 new java.util.Date((long)timeStamp);
From the documentation:
从文档:
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
分配一个 Date 对象并将其初始化为表示自称为“纪元”的标准基准时间(即格林威治标准时间 1970 年 1 月 1 日 00:00:00)以来的指定毫秒数。
回答by f1sh
Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass is to the constructor.
Date 的构造函数期望 timeStamp 值以毫秒为单位。将时间戳的值乘以 1000,然后传递给构造函数。
回答by Marco Fantasia
This is the right way:
这是正确的方法:
Date date = new Date ();
date.setTime((long)unix_time*1000);
回答by Stefan
Looks like Calendar is the new way to go:
看起来日历是一种新的方式:
Calendar mydate = Calendar.getInstance();
mydate.setTimeInMillis(timestamp*1000);
out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));
The last line is just an example how to use it, this one would print eg "14.06.2012".
最后一行只是一个如何使用它的例子,这一行会打印例如“14.06.2012”。
If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.
如果您使用 System.currentTimeMillis() 保存时间戳,则不需要“*1000”部分。
If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).
如果字符串中有时间戳,则需要首先将其解析为 long:Long.parseLong(timestamp)。
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
回答by tmr
If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;
如果您在另一台机器上转换时间戳值,您还应该检查该机器的时区。例如;
The above decriptions will result different Date values, if you run with EST or UTC timezones.
如果您使用 EST 或 UTC 时区运行,上述描述将导致不同的日期值。
To set the timezone; aka to UTC, you can simply rewrite;
设置时区;也就是UTC,你可以简单地重写;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
回答by micha
java.time
时间
Java 8introduced a new API for working with dates and times: the java.time package.
Java 8引入了一个用于处理日期和时间的新 API:java.time 包。
With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant
.
使用 java.time,您可以解析自 UTC 中 1970 年第一时刻的纪元参考 1970-01-01T00:00Z 以来的整秒计数。结果是一个Instant
.
Instant instant = Instant.ofEpochSecond( timeStamp );
If you need a java.util.Date
to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.
如果您需要java.util.Date
与尚未为java.time更新的旧代码进行互操作,请转换。调用添加到旧类的新转换方法。
Date date = Date.from( instant );
回答by Basil Bourque
tl;dr
tl;博士
Instant.ofEpochSecond( 1_280_512_800L )
2010-07-30T18:00:00Z
2010-07-30T18:00:00Z
java.time
时间
The new java.time framework built into Java 8 and later is the successor to Joda-Time.
Java 8 及更高版本中内置的新 java.time 框架是 Joda-Time 的继承者。
These new classes include a handy factory method to convert a count of whole secondsfrom epoch. You get an Instant
, a moment on the timeline in UTC with up to nanoseconds resolution.
这些新类包括一个方便的工厂方法,用于从纪元转换整秒的计数。您会Instant
在 UTC 时间轴上获得一个时刻,分辨率高达纳秒。
Instant instant = Instant.ofEpochSecond( 1_280_512_800L );
instant.toString(): 2010-07-30T18:00:00Z
Instant.toString(): 2010-07-30T18:00:00Z
See that code run live at IdeOne.com.
Asia/Kabul
or Asia/Tehran
time zones ?
Asia/Kabul
或Asia/Tehran
时区?
You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z
(short for Zulu
, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul
or Asia/Tehran
time zones? I suppose so as you report IRST
in your output which apparently means Iran time. Currently in 2017 those are the only zonesoperating with a summer time that is four and a half hours ahead of UTC.
您报告获得的时间值为 22:30,而不是此处看到的 18:00。我怀疑您的 PHP 实用程序正在隐式应用默认时区以根据 UTC 进行调整。我这里的值是 UTC,由Z
( 的缩写Zulu
,表示 UTC)表示。您的机器操作系统或 PHP 是否有可能设置为Asia/Kabul
或Asia/Tehran
时区?我想你IRST
在你的输出中报告这显然意味着伊朗时间。目前在 2017 年,这些是唯一一个夏令时比 UTC 早四个半小时的区域。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
or IRST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。切勿使用 3-4 个字母的缩写,例如or或,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
IRST
If you wantto see your moment through the lens of a particular region's time zone, apply a ZoneId
to get a ZonedDateTime
. Still the same simultaneous moment, but seen as a different wall-clock time.
如果您想通过特定地区时区的镜头查看您的时刻,请应用 aZoneId
以获得ZonedDateTime
. 仍然是同一时刻,但被视为不同的挂钟时间。
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z ); // Same moment, same point on timeline, but seen as different wall-clock time.
2010-07-30T22:30+04:30[Asia/Tehran]
2010-07-30T22:30+04:30[亚洲/德黑兰]
Converting from java.time to legacy classes
从 java.time 转换为遗留类
You should stick with the new java.time classes. But you can convert to old if required.
您应该坚持使用新的 java.time 类。但如果需要,您可以转换为旧的。
java.util.Date date = java.util.Date.from( instant );
Joda-Time
乔达时间
UPDATE: The Joda-Timeproject is now in maintenance mode, with the team advising migration to the java.timeclasses.
更新:Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。
FYI, the constructor for a Joda-TimeDateTimeis similar: Multiply by a thousand to produce a long
(not an int
!).
仅供参考,Joda-Time DateTime的构造函数是类似的:乘以一千产生一个long
(不是一个int
!)。
DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );
Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.
最好避免臭名昭著的 java.util.Date 和 .Calendar 类。但是,如果您必须使用日期,则可以从 Joda-Time 转换。
java.util.Date date = dateTime.toDate();
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。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。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 (<26), 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-反向移植。
- 安卓
- java.time 类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),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
,和更多。
回答by Masatsugu Hosoi
Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());
回答by Arda Kazanc?
For kotlin
对于科特林
fun unixToDate(timeStamp: Long) : String? {
val time = java.util.Date(timeStamp as Long * 1000)
val sdf = SimpleDateFormat("yyyy-MM-dd")
return sdf.format(time)
}