Java 如何从日历中获取 UTC 时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4377279/
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 do I get a UTC Timestamp from Calendar?
提问by Jonas
In Java when I use Calendar.getInstance();
I get a Calendar
object for the current Timezone. But java.sql.Timestamp
is usually stored in UTC Time and not in local time. So how can I get the UTC Time from a Calendar instance?
在 Java 中,当我使用时,Calendar.getInstance();
我会得到一个Calendar
当前时区的对象。但java.sql.Timestamp
通常存储在 UTC 时间而不是本地时间。那么如何从 Calendar 实例中获取 UTC 时间呢?
DateFormat df = DateFormat.getTimeInstance();
Calendar cal = Calendar.getInstance();
Timestamp time = new Timestamp(cal.getTimeInMillis());
// Prints local time
System.out.println(df.format(new Date(time.getTime())));
// Printe local time, but I want UTT Time
System.out.println("timestamp: " + time);
采纳答案by Jon Skeet
When you call Calendar.getTime()
, that will give you a value which doesn't have a related time zone - or you could think of it as being in UTC - for the instantthat the calendar represents. So if it was (say) 9am in the calendar's time zone, it could be 5pm UTC.
当您调用Calendar.getTime()
时,它将为您提供一个没有相关时区的值 - 或者您可以将其视为 UTC - 对于日历所代表的时刻。因此,如果是(比如说)日历时区的上午 9 点,则可能是 UTC 下午 5 点。
Now java.util.Date
(and I'd imagine Timestamp
) will be formattedin the system default time zone when you call toString()
(whether implicitly or explicitly) - but don't let that fool you into thinking that the time zone is part of the data within the object itself.
现在java.util.Date
(我想Timestamp
)将在您调用时(无论是隐式还是显式)格式化为系统默认时区toString()
- 但不要让这愚弄您认为时区是对象本身内的数据的一部分.
You need to be very clear about exactlywhat you're trying to achieve - and then you'll probably find that Joda Timelets you express that in code more clearly than the built-in libraries do.
你必须非常清楚有关正是你想要什么来实现-然后你可能会发现,约达时间可以让你表达的代码更明显比内置库做。
回答by Michael Borgwardt
Your code is already doing exactly what you want. Timestamp
(as well as Date
) does not have timezone information and should always contain a GMT timestamp (which ist what Calendar.getTimeInMillis()
returns).
您的代码已经完全符合您的要求。Timestamp
(以及Date
)没有时区信息,并且应始终包含 GMT 时间戳(Calendar.getTimeInMillis()
返回的内容)。
The reson why you see local time printed is that the DateFormat
factory methods as well as Timestamp.toString()
implicitly use the system timezone.
您看到本地时间打印的原因是DateFormat
工厂方法以及Timestamp.toString()
隐式使用系统时区。
回答by Prashanth
Following snippet should satisfy your requirements:
以下代码段应满足您的要求:
df.setTimeZone(TimeZone.getTimeZone("UTC"));
回答by Basil Bourque
tl;dr
tl;博士
Instant.now()
Avoid legacy date-time classes
避免遗留的日期时间类
You are using troublesome old date-time classes now supplanted by the java.time classes. No need to be using DateFormat
, Calendar
, or Timestamp
.
您正在使用麻烦的旧日期时间类,现在已被 java.time 类取代。无需使用DateFormat
, Calendar
, 或Timestamp
。
If you must interopt with a Calendar
from old code not yet updated to java.time, convert using new methods added to the old classes. Extract an obsolete java.util.Date
, and convert to Instant
.
如果必须与Calendar
尚未更新到 java.time 的旧代码互操作,请使用添加到旧类的新方法进行转换。提取一个过时的java.util.Date
,并转换为Instant
.
Instant instant = myCal.getTime().toInstant() ;
Using java.time
使用 java.time
Get the current moment as 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).
获取当前时刻作为Instant
. 该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
Instant instant = Instant.now() ;
2017-02-17T03:29:15.725Z
2017-02-17T03:29:15.725Z
Database
数据库
With JDBC 4.2 and later, you can directly exchange a Instant
object with your database. So no need for the obsolete java.sql.Timestamp
.
使用 JDBC 4.2 及更高版本,您可以直接Instant
与数据库交换对象。所以不需要过时的java.sql.Timestamp
。
myPreparedStatement.setObject( … , instant ) ;
And retrieval:
并检索:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Count from epoch
从纪元开始计数
Apparently you want a number of milliseconds since the epoch reference dateof 1970-01-01T00:00:00Z
. You can extract that number from an Instant
. But beware of data loss, as a Instant
has a resolution of nanoseconds which you will be truncating to milliseconds.
显然,你想了许多,因为毫秒历元基准日期的1970-01-01T00:00:00Z
。您可以从Instant
. 但要注意数据丢失,因为 aInstant
的分辨率为纳秒,您将截断为毫秒。
long millis = instant.toEpochMilli() ;
1487302155725
1487302155725
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。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8and SE 9and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8和SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用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
,和更多。