阅读您的问题后,我假设您的方法 message.getHeader().getUtcTimeStamp(SendingTime.FIELD) 返回一个 String(不是 LocalDateTime),表示 UTC 中的时间戳,同时格式为 2020-06-29 05:31:58.153 或 2020-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");
}
当然,对于仅等于秒的日期时间,此输出是不同的:
-
2020-06-29T05:31:58Z[UTC] ==> 1593408718000纪元毫秒
-
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");
}
输出:
2020-06-29T05:31:58Z[UTC] ==> 1593408718 epoch seconds
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");
}