如何将时间戳从GMT转换为Unix时期

发布于 2025-02-13 08:24:47 字数 924 浏览 1 评论 0原文

我正在解析“ 2022-01-12T17:17:34.512492+0000” 的时间戳。 sssss'zzzz“ (ISO8601)。

我想在epoch unix时间转换它,我正在使用java.text.simpledateformat。 我尝试了两种方法,但两者都不起作用:

1-第一个方法

val parsed = "2022-01-12T17:17:34.512492+0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ'")
val date = df.parse(parsed.toString)
val epoch = date.getTime

错误显示:

java.text.ParseException: Unparseable date: "2022-01-12T17:17:34.512492+0000"

2-第二种方法显示了输出,但

val parsed = "2022-01-12T17:17:34.512492+0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'+0000'")
val date = df.parse(parsed.toString)
val epoch = date.getTime
println(epoch)

输出不正确:

1642004766492

如果将此时代转换为人类日期:” 2022年1月12日,星期三16 :26:06.492“

小时,分钟和秒是错误的。

I'm parsing a timestamp which is "2022-01-12T17:17:34.512492+0000", this format is "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ" (ISO8601).

I want to convert it in epoch unix time, I'm using java.text.SimpleDateFormat.
I tried two methods but both don't work:

1- First Method

val parsed = "2022-01-12T17:17:34.512492+0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ'")
val date = df.parse(parsed.toString)
val epoch = date.getTime

Error showed:

java.text.ParseException: Unparseable date: "2022-01-12T17:17:34.512492+0000"

2- This second Method shows an output but is incorrect

val parsed = "2022-01-12T17:17:34.512492+0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'+0000'")
val date = df.parse(parsed.toString)
val epoch = date.getTime
println(epoch)

Output:

1642004766492

If you convert this epoch to HUMAN DATE: "Wednesday, 12 January 2022 16:26:06.492"

The hours,minutes and seconds are wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

戏蝶舞 2025-02-20 08:24:47

正如Gael指出的那样,SimpleDateFormat已过时。

API现在支持纳秒秒,因此微秒并不是这里的问题。您应该使用 datement formatter 代码> ZonedDateTime 。您的模式有点错。检查偏移Z的文档:

偏移Z:这是根据模式数量格式化偏移的格式
信件。一个,两个或三个字母输出一个小时和分钟,
没有结肠,例如“ +0130”。当输出为“ +0000”
偏移为零。四个字母输出本地化的完整形式
偏移,相当于四个偏移o的字母。输出将是
相应的本地化偏移文本如果偏移为零。五
字母输出小时,分钟,如果非零,则以可选的第二次输出,
与结肠。如果偏移为零,它将输出“ Z”。六个或更多字母
扔非法的exception。

您还可以使用toinstant打印时间以确保正确解析它:

  import java.time.ZonedDateTime
  import java.time.format.DateTimeFormatter

  val parsed = "2022-01-12T17:17:34.512492+0000"
  val p = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZ"
  val dtf = DateTimeFormatter.ofPattern(p)
  val zdt = ZonedDateTime.parse(parsed, dtf)
  println(zdt.toInstant) // 2022-01-12T17:17:34.512492Z
  println(zdt.toInstant.toEpochMilli) // 1642004254512

这是不错的文章 详细解释了Java中ISO 8601的详细说明。最后的评论特别有用,因为它显示了所使用的不同模式之间的差异。

SimpleDateFormat is outdated, as Gael pointed out.

The Time API now supports up to nanoseconds, so microseconds are not an issue here. You should use DateTimeFormatter with ZonedDateTime. Your pattern is slightly wrong. Checking the docs for Offset Z:

Offset Z: This formats the offset based on the number of pattern
letters. One, two or three letters outputs the hour and minute,
without a colon, such as '+0130'. The output will be '+0000' when the
offset is zero. Four letters outputs the full form of localized
offset, equivalent to four letters of Offset-O. The output will be the
corresponding localized offset text if the offset is zero. Five
letters outputs the hour, minute, with optional second if non-zero,
with colon. It outputs 'Z' if the offset is zero. Six or more letters
throws IllegalArgumentException.

You can also print the time using toInstant to make sure it was parsed correctly:

  import java.time.ZonedDateTime
  import java.time.format.DateTimeFormatter

  val parsed = "2022-01-12T17:17:34.512492+0000"
  val p = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZ"
  val dtf = DateTimeFormatter.ofPattern(p)
  val zdt = ZonedDateTime.parse(parsed, dtf)
  println(zdt.toInstant) // 2022-01-12T17:17:34.512492Z
  println(zdt.toInstant.toEpochMilli) // 1642004254512

Here is a nice article that explains in detail converting an ISO 8601 in Java. The comments at the end are particularly useful, as it shows the difference between the different patterns used.

梦途 2025-02-20 08:24:47

看起来Epoch具有内部DateTime格式的数据。
您应该将其转换为字符串格式
像这样在爪哇

    public static String dateToString(Date d, String string_format) {
        String result = "";
        if(d != null) {
            result = new SimpleDateFormat(string_format).format(d);
        }
        return result;
    }

looks like epoch has data in internal datetime format.
and you should convert it to string format
like this in java

    public static String dateToString(Date d, String string_format) {
        String result = "";
        if(d != null) {
            result = new SimpleDateFormat(string_format).format(d);
        }
        return result;
    }
拥抱没勇气 2025-02-20 08:24:47

您拥有微秒精度的时间戳。 SimpleDateFormat不支持这种精度。同样,Unix时期时间通常达到毫秒精度。

这里可能的解决方案是在解析之前将微秒明确到字符串中的毫秒到毫秒,然后使用yyyy-mm-dd'hh:mm:mm:ss.sssz格式。

String parsed = "2022-01-12T17:17:34.512492+0000";

String upToSeconds = parsed.substring(0, "yyyy-MM-ddTHH:mm:ss".length());
String microseconds = parsed.substring("yyyy-MM-ddTHH:mm:ss.".length(), "yyyy-MM-ddTHH:mm:ss.".length() + "SSSSSS".length());
String timezone = parsed.substring("yyyy-MM-ddTHH:mm:ss.SSSSSS".length());

String roundedMilliseconds = new BigDecimal(microseconds).divide(new BigDecimal("1000"), 0, RoundingMode.HALF_UP).toString();

String reformatted = upToSeconds + "." + roundedMilliseconds + timezone;
System.out.println(reformatted); // 2022-01-12T17:17:34.512+0000

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
long epoch = sdf.parse(reformatted).getTime();

System.out.println(epoch); // 1642007854512
System.out.println(Instant.ofEpochMilli(epoch)); // 2022-01-12T17:17:34.512Z

The timestamp you have has microseconds precision. Such precision is not supported by SimpleDateFormat. Also, Unix epoch time is usually up to milliseconds precision.

Possible solution here is to explicitly round the microseconds to milliseconds in the string before parsing, then use the yyyy-MM-dd'T'HH:mm:ss.SSSZ format.

String parsed = "2022-01-12T17:17:34.512492+0000";

String upToSeconds = parsed.substring(0, "yyyy-MM-ddTHH:mm:ss".length());
String microseconds = parsed.substring("yyyy-MM-ddTHH:mm:ss.".length(), "yyyy-MM-ddTHH:mm:ss.".length() + "SSSSSS".length());
String timezone = parsed.substring("yyyy-MM-ddTHH:mm:ss.SSSSSS".length());

String roundedMilliseconds = new BigDecimal(microseconds).divide(new BigDecimal("1000"), 0, RoundingMode.HALF_UP).toString();

String reformatted = upToSeconds + "." + roundedMilliseconds + timezone;
System.out.println(reformatted); // 2022-01-12T17:17:34.512+0000

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
long epoch = sdf.parse(reformatted).getTime();

System.out.println(epoch); // 1642007854512
System.out.println(Instant.ofEpochMilli(epoch)); // 2022-01-12T17:17:34.512Z
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文