简体   繁体   English

将日期时间字符串转换为Unix时间戳

[英]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. 日期时间字符串将始终采用该格式。

java.time and ThreeTen Backport java.time和ThreeTen反向移植

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

Question: How can I use ZonedDateTime and DateTimeFormatter on Java 7? 问题:如何在Java 7上使用ZonedDateTime和DateTimeFormatter?

I am still on Java 7 btw so can't use ZonedDataTime and DateTimeFormatter but I can use joda library. 我仍然在Java 7 btw上,因此不能使用ZonedDataTimeDateTimeFormatter但可以使用joda库。

Indeed you can. 确实可以。 java.time just requires at least Java 6 . java.time至少需要Java 6

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. 在Java 8和更高版本以及更新的Android设备(来自API级别26)中,内置了现代API。
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom). 在Java 6和7中,获取ThreeTen Backport,这是现代类的backport(JSR 310的ThreeTen;请参见底部的链接)。
  • On (older) Android use the Android edition of ThreeTen Backport. 在较旧的Android上,请使用Android版本的ThreeTen Backport。 It's called ThreeTenABP. 它称为ThreeTenABP。 And make sure you import the date and time classes from 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似乎是永不过时的解决方案。

Links 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM