[英]convert date time string to unix timestamp
I have a string for date time coming as like this without any spaces in between them: 我有一个日期时间的字符串,像这样,它们之间没有任何空格:
TueDec2618:47:09UTC2017
Is there any way to convert this to unix timestamps? 有什么办法可以将其转换为Unix时间戳吗? The date time string will always be in that format. 日期时间字符串将始终采用该格式。
The comment by ernest_k is well thought out and solves your issue: ernest_k的评论经过深思熟虑 ,可以解决您的问题:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEEMMMddHH:mm:sszyyyy", Locale.ENGLISH);
String dateTimeString = "TueDec2618:47:09UTC2017";
ZonedDateTime dateTime = ZonedDateTime.parse(dateTimeString, formatter);
long unixTimestamp = dateTime.toEpochSecond();
System.out.println("Parsed date-time " + dateTime + " Unix timestamp " + unixTimestamp);
The output from running on ThreeTen Backport 1.3.6, tested on Java 1.7.0_79, is: 在Java 1.7.0_79上测试的在ThreeTen Backport 1.3.6上运行的输出为:
Parsed date-time 2017-12-26T18:47:09Z[Zulu] Unix timestamp 1514314029 解析的日期时间2017-12-26T18:47:09Z [Zulu] Unix时间戳1514314029
I am still on Java 7 btw so can't use
ZonedDataTime
andDateTimeFormatter
but I can use joda library. 我仍然在Java 7 btw上,因此不能使用ZonedDataTime
和DateTimeFormatter
但可以使用joda库。
Indeed you can. 确实可以。 java.time just requires at least Java 6 . java.time至少需要Java 6 。
org.threeten.bp
with subpackages. 并确保使用子包从org.threeten.bp
导入日期和时间类。 While Joda-Time would be another nice solution, I believe that you should prefer the ThreeTen Backport over Joda-Time (though opinions differ). 尽管Joda-Time是另一个不错的解决方案,但我认为您应该选择ThreeTen Backport而不是Joda-Time(尽管意见分歧)。 The Joda-Time home page advises: Joda-Time主页建议:
Note that Joda-Time is considered to be a largely “finished” project. 请注意,Joda-Time被认为是一个很大的“完成”项目。 No major enhancements are planned. 没有计划进行重大增强。 If using Java SE 8, please migrate to
java.time
(JSR-310). 如果使用Java SE 8,请迁移到java.time
(JSR-310)。
So java.time seems to be the future-proof solution. 因此,java.time似乎是永不过时的解决方案。
java.time
was first described. Java Specification Request(JSR)310 ,其中首先描述了java.time
。 java.time
to Java 6 and 7 (ThreeTen for JSR-310). ThreeTen Backport项目 ,即java.time
到Java 6和7的java.time
移植(JSR-310的ThreeTen)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.