java 如何将 ISO8601 格式转换为毫秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26519867/
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 to convert ISO8601 format into milliseconds?
提问by David
I'm pretty surprised that I haven't yet found a really easy way considering how often ISO8601 is used in JSON.
考虑到 ISO8601 在 JSON 中的使用频率,我还没有找到一种非常简单的方法,这让我感到非常惊讶。
Basically, I'm taking a string that looks like this: 2014-10-23T00:35:14.800Z
and converting it into something like 50 minutes ago
.
基本上,我正在使用一个看起来像这样的字符串:2014-10-23T00:35:14.800Z
并将其转换为类似50 minutes ago
.
First, I have to change 2014-10-23T00:35:14.800Z
to 2014-10-23'T'00:35:14.800Z
, then I need to convert it to milliseconds, then it is easy.
首先,我必须更改2014-10-23T00:35:14.800Z
为2014-10-23'T'00:35:14.800Z
,然后我需要将其转换为毫秒,然后就很容易了。
My current code:
我目前的代码:
private void setTimestamp(String timeCreated) {
int indexOfT = timeCreated.indexOf('T');
String properFormat = new StringBuilder(timeCreated).insert(indexOfT + 1, "'")
.insert(indexOfT, "'")
.toString();
timeStamp = (String) DateUtils.getRelativeTimeSpanString(Long.parseLong(properFormat),
System.currentTimeMillis(),
DateUtils.SECONDS_IN_MILLIS);
}
The culprit is Long.parseLong(properFormat)
. I need to convert properFormat
into milliseconds.
罪魁祸首是Long.parseLong(properFormat)
。我需要转换properFormat
成毫秒。
回答by Basil Bourque
tl;dr
tl;博士
Instant.parse( "2014-10-23T00:35:14.800Z" )
.toEpochMilli()
One-Liner In java.time
java.time 中的单行
The java.timeframework is built into Java 8 and later. These new classes supplant the old date-time classes bundled with the earliest versions of Java such as java.util.Date/.Calendar. See Tutorial. The java.time classes also supplant the highly successful Joda-Timelibrary, being built by some of the same folks including being led by the same Stephen Colbourne.
该java.time框架是建立在Java 8和更高版本。这些新类取代了与 Java 最早版本(例如 java.util.Date/.Calendar)捆绑在一起的旧日期时间类。请参阅教程。java.time 类还取代了非常成功的Joda-Time库,该库由一些相同的人构建,包括由相同的Stephen Colbourne领导。
An Instant
is a moment on the timeline in UTCwith a resolution of nanoseconds. You can ask it for a count of millisecondsfrom its epoch(first moment of 1970 in UTC). But remember that an Instant
may have additional data, nanoseconds being finer than milliseconds. So you may be losing datain that tiny fraction of a fraction of a second.
AnInstant
是UTC时间线上的一个时刻,分辨率为纳秒。您可以要求它从其纪元(UTC 中的 1970 年的第一个时刻)开始计算毫秒数。但请记住,一个Instant
可能有额外的数据,纳秒比毫秒更精细。因此,您可能会在几分之一秒内丢失数据。
The java.time classes use standard ISO 8601 formats when parsing/generating strings. No need to specify a formatting pattern. The Instant
class can directly parsea string.
java.time 类在解析/生成字符串时使用标准 ISO 8601 格式。无需指定格式模式。本Instant
类可以直接解析字符串。
Instant.parse( "2014-10-23T00:35:14.800Z" )
You can convert that to a count of milliseconds since the epoch of first moment of 1970 in UTC by calling toEpochMilli
您可以通过调用将其转换为自 UTC 中 1970 年第一时刻以来的毫秒数 toEpochMilli
Be aware of possible data loss as the Instant
class can hold nanoseconds. So extracting milliseconds will be truncating any microseconds or nanoseconds in any fractional second. Your example string has only three digits in the fractional second, so that is only milliseconds. But six or nine digits of decimal fraction would be truncated to three when converted to a count of milliseconds.
请注意可能的数据丢失,因为Instant
该类可以保持纳秒。因此,提取毫秒将在任何小数秒内截断任何微秒或纳秒。您的示例字符串在小数秒中只有三位数字,因此只有毫秒。但是,当转换为毫秒计数时,十进制小数的六位或九位将被截断为三。
long millisFromEpoch = Instant.parse( "2014-10-23T00:35:14.800Z" ).toEpochMilli();
To get elapsed time in terms of hours-minutes-seconds, use the Duration
class. Feed its between
method a pair of moments in time.
要以小时-分钟-秒为单位获取经过时间,请使用Duration
该类。between
及时为其方法提供一对时刻。
Duration duration = Duration.between( Instant.parse( "2014-10-23T00:35:14.800Z" ) , Instant.now() );
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, Java SE 10, 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 SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
One-Liner In Joda-Time
Joda-Time 中的单线
UPDATE:The Joda-Time project is in maintenance mode, with the team advising migration to the java.time classes.
更新:Joda-Time 项目处于维护模式,团队建议迁移到 java.time 类。
With the Joda-Time2.5 library:
使用Joda-Time2.5 库:
long millisSinceEpoch = new DateTime( "2014-10-23T00:35:14.800Z" ).getMillis();
Joda-Time parses and generates ISO 8601strings by default. Joda-Time works in Android. The java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.
Joda-Time默认解析并生成ISO 8601字符串。Joda-Time 适用于 Android。java.util.Date/.Calendar 类是出了名的麻烦、混乱和有缺陷。避开它们。
回答by David
So, turns out the answer was simpler than I would have imagined.
所以,结果证明答案比我想象的要简单。
private void setTimestamp(String timeCreated) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
Date timeCreatedDate = dateFormat.parse(timeCreated);
timeStamp = (String) DateUtils.getRelativeTimeSpanString(timeCreatedDate.getTime(),
System.currentTimeMillis(),
DateUtils.SECONDS_IN_MILLIS);
} catch ( ParseException e) {}
}
That'll work.
那行得通。