简体   繁体   English

JAVA 从 ISO_DATE_TIME 获取自纪元以来的毫秒数

[英]JAVA Get Milliseconds since Epoch from ISO_DATE_TIME

I'm trying to get Milliseconds since Epoch from ISO_DATE_TIME and i have been reading so many article.我试图从 ISO_DATE_TIME 获得自 Epoch 以来的毫秒数,并且我已经阅读了很多文章。

My starting point is this: 2020-10-06T11:51:45.964+01:00我的出发点是这样的: 2020-10-06T11:51:45.964+01:00

My ending point is a long that consider milliseconds.我的终点是一个考虑毫秒的 ( https://currentmillis.com/ ) ( https://currentmillis.com/ )

I'm using a message coming from Kafka into Flink, and the time stamp is in the payload of the message.我正在使用来自 Kafka 的消息到 Flink,时间戳在消息的有效负载中。

This is my code:这是我的代码:

public void setKafkaTime(String kafkaTime) {
    DateTimeFormatter sdr = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXXX");
    LocalDateTime MydateTime = LocalDateTime.parse(kafkaTime,sdr);
    NOT WORKING -> Date date = Date.from(MydateTime.toInstant(ZoneOffset.UTC));
    Long tn = date.getTime();
    this.time = tn;
}

There is so much about the topic and i tried many ways, starting from the Java doc:关于这个主题有很多,我尝试了很多方法,从 Java 文档开始:

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE_TIME But mine is not ISO-8601 standard as i have second and milliseconds. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE_TIME但我的不是 ISO-8601 标准,因为我有秒和毫秒。

i have been using some important tips from previous questions like this one, where i found the pattern Java string to date conversion and i got this nice table.我一直在使用以前问题中的一些重要提示,例如这个问题,在那里我找到了模式Java 字符串到日期的转换,并得到了这张漂亮的表格。 在此处输入图片说明

To use .getTime() I need a java.util.Date to convert LocalDateTime to Date I got in trouble with an error asking me for a Java.sql.Date.要使用 .getTime(),我需要一个java.util.DateLocalDateTime转换为Date我遇到了一个错误,要求我提供Java.sql.Date。

在此处输入图片说明

I have been reading about the difference between the two, and from what I understood Java.sql doesn't consider the time, so I denfinetly should not use it.我一直在阅读两者之间的区别,据我了解 Java.sql 不考虑时间,所以我不应该使用它。

java.util.Date vs java.sql.Date java.util.Date 与 java.sql.Date

I'm confident about the top two lines of the code, for the rest I'm struggling.我对代码的前两行充满信心,其余的我都在努力。 I really can't get how to obtain a long.我真的不知道如何获得一个长。 Any help would be really appreciated.任何帮助将非常感激。

Thanks谢谢

Try this.尝试这个。 I used a zoned time and then converted that to an instant to get the milliseconds.我使用了分区时间,然后将其转换为瞬间以获得毫秒。

public  void setKafkaTime(String kafkaTime) {
    DateTimeFormatter sdr = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSzzz");
    ZonedDateTime MydateTime = ZonedDateTime.parse(kafkaTime,sdr);
    this.time = MydateTime.toInstant().toEpochMilli();
}

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

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