【问题标题】:converting timestamp date to unix timestamp将时间戳日期转换为 unix 时间戳
【发布时间】:2020-10-19 06:24:13
【问题描述】:

我有这样的数据 我从时间戳 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 怎么转换?

【问题讨论】:

  • @ScaryWombat 该类应该永远在实际的 JDBC 代码中除外。
  • Date currentDate = new Date(); long t = currentDate.getTime()/1000;
  • @chrylis-cautiouslyoptimistic- 同意,不知何故,对于他预先编辑的问题,我做出了一个错误的假设,即他也有Timestamp
  • 您是否收到任何错误消息?有什么错误的结果吗?请报价。另外你的搜索结果是什么?它以什么方式不足或不起作用? I downvoted because research must be done to ask a good question.

标签: java timestamp unix-timestamp


【解决方案1】:

如果您的getUtcTimeStamp 方法足以返回LocalDateTime,那么您就大功告成了。使用ldt.atOffset(ZoneOffset.UTC) 转换为Instant (如果您的getUtcTimeStamp 已经知道它是UTC,那么它真的应该为您执行此操作),然后只需调用toEpochSecond()(或toEpochMilli(),如果您想要毫秒部分,但是你只显示了整秒)。

【讨论】:

    【解决方案2】:

    阅读您的问题后,我假设您的方法 message.getHeader().getUtcTimeStamp(SendingTime.FIELD) 返回一个 String(不是 LocalDateTime),表示 UTC 中的时间戳,同时格式为 2020-06-29 05:31:58.1532020-06-29 05:31:58

    由于您有(显示)不同格式的日期时间(分别具有不同精度的日期时间),您必须通过使用能够处理可选毫秒的模式(yyyy-MM-dd HH:mm:ss[.SSS])定义一个合适的DateTimeFormatter )。

    您可以按如下方式使用它:

    public static void main(String[] args) {
        // receive the result from your message, this is just an example
        String utcTimestamp = "2020-06-29 05:31:58";
        // create a ZonedDateTime by parsing the String to a LocalDateTime and adding a time zone
        ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
                                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
                             .atZone(ZoneId.of("UTC"));
        // then get the epoch milliseconds / unix timestamp
        long millis = zdt.toInstant().toEpochMilli();
        // and print the result
        System.out.println(zdt + " ==> " + millis + " epoch millis");
    }
    

    当然,对于仅等于秒的日期时间,此输出是不同的:

    1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718000纪元毫秒
    2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718153纪元毫秒

    如果您调用 long seconds = zdt.toEpochSeconds() 而不是转换 toInstant().toEpochMillis(并稍微调整输出),您将得到两个示例的相同值:

    public static void main(String[] args) {
        // receive the result from your message, this is just an example
        String utcTimestamp = "2020-06-29 05:31:58.153";
        // create a ZonedDateTime by parsing the String to a LocalDateTime and adding a time zone
        ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
                                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
                             .atZone(ZoneId.of("UTC"));
        // then get the epoch seconds
        long seconds = zdt.toEpochSecond();
        // and print the result
        System.out.println(zdt + "\t==>\t" + seconds + " epoch seconds");
    }
    

    输出:

    1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718 epoch seconds
    2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718 epoch seconds

    如果您的方法确实返回 LocalDateTime,您可以简单地跳过转换并编写

    public static void main(String[] args) {
        LocalDateTime utcDateTime = message.getHeader().getUtcTimeStamp(SendingTime.FIELD); 
        // then get the epoch seconds
        long seconds = utcDateTime.atZone(ZoneId.of("UTC")).toEpochSecond();
        // and print the result
        System.out.println(utcDateTime + "\t==>\t" + seconds + " epoch seconds");
    }
    

    【讨论】:

    • 是的,我的经纪人有任何毫秒,例如 2020-06-29 05:31:58.153 但我想在没有毫秒的情况下保存,因为如果我想从我的数据库中获取价格,我只想检查第二个和我朋友一样
    • @yuyukungkung 好的,好的...请查看最后的编辑...
    【解决方案3】:

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

    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 可以为我们买单。

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 1970-01-01
      • 2020-12-23
      • 2016-04-24
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多