Having read your question, I assume your method message.getHeader().getUtcTimeStamp(SendingTime.FIELD)
returns a String
(not a LocalDateTime
) representing a timestamp in UTC while being formatted either like 2020-06-29 05:31:58.153
or 2020-06-29 05:31:58
.
Since you have (shown) differently formatted datetimes (respectively, datetimes with a different accuracy), you will have to take care of that by defining a suitable DateTimeFormatter
using a pattern able to deal with optional milliseconds (yyyy-MM-dd HH:mm:ss[.SSS]
).
You can use it as follows:
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");
}
The output of this is, of course, different for datetimes that are only equal down to seconds:
2020-06-29T05:31:58Z[UTC] ==> 1593408718000
epoch millis
2020-06-29T05:31:58.153Z[UTC] ==> 1593408718153
epoch millis
If you call long seconds = zdt.toEpochSeconds()
instead of converting toInstant().toEpochMillis
(and adjust the output a little) you will get the same value for both examples:
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");
}
Output:
2020-06-29T05:31:58Z[UTC] ==> 1593408718 epoch seconds
2020-06-29T05:31:58.153Z[UTC] ==> 1593408718 epoch seconds
If your method really returns a LocalDateTime
, you could simply skip conversions and write
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");
}