首页 > 解决方案 > 将时间戳日期转换为 unix 时间戳

问题描述

我有这样一个日期的数据,我从时间戳 UTC 得到的是:2020-06-29 05:31:58.153

 LocalDateTime timestampasstring = message.getHeader().getUtcTimeStamp( SendingTime.FIELD);
 Timestamp timestamp = Timestamp.from(timestampasstring.toInstant(ZoneOffset.UTC));
 System.out.println(timestamp);
 String timestampstrings = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
 String timestampstrings2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timestamp);

我需要获取像 2020-06-29 05:31:58 这样的时间戳编号并将其转换为像这样的 unix 时间戳 1593408718 如何转换它?

标签: javatimestampunix-timestamp

解决方案


其他答案都很好。这是我的变种。首先声明一个用于解析的格式化程序:

private DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral(' ')
        .append(DateTimeFormatter.ISO_LOCAL_TIME)
        .toFormatter();

考虑声明格式化程序static和/或final. 使用这个格式化程序,我会这样做:

    String timestampAsString = "2020-06-29 05:31:58.153";
    
    OffsetDateTime dateTime = LocalDateTime
            .parse(timestampAsString, timestampFormatter)
            .atOffset(ZoneOffset.UTC);
    long unixTimestamp = dateTime.toEpochSecond();
    
    System.out.println(unixTimestamp);

输出是您要求的:

1593408718

格式化程序的好处是它同时接受2020-06-29 05:31:58.1532020-06-29 05:31:58,也就是说,时间有和没有秒的分数,以及从 1 到 9 位小数的任何分数。在格式化程序中重用ISO_LOCAL_TIME为我们买了这个。


推荐阅读