Ho to convert epoch timestamp to zonedDateTime?

I am receiving a timestamp value as output from a exec-binding command. As I have to parse it out of a longer string, the type of the 13 digit value is String (e.g. 1666275807). Now I would like to transform this to a normal date in zonedDateTime format. How can I do this in Rules DSL?

Thank you for any hints!

Try this - I think it still works:

Unfortunately this is not working anymore in OH3 (it seems that the old rule code from 2015 comes from OH1 with Joda Time). How can this be done with the now used ZonedDateTime?

oh. Right! It was Joda-time back then…

I’m honest, I don’t know how it’s done with DSL only, but with a JS-transformation it should work, you even don’t need a rule for it then:

you could use the exec binding to return the date in zonedDateTime format instead of epoch format

date  -d @1666275807
Thu 20 Oct 2022 04:23:27 PM CEST

Something like the following should work.

val results = // how ever you get the epoch as a String
val resultsLong = new BigDecimal(results).longValue
val instant = java.time.Instant.ofEpochSecond(resultsLong)
val tz = now.zone // default time zone
ZonedDateTime.ofInstant(instant, tz)

Be careful with that second line of code. If your exec returns a newline BigDecimal won’t be able to parse it. You’ll have to strip extraneous characters off of it. Often this is as easy as calling results.trim.

2 Likes

Thank you very much Rich, like always your advice is simply the best :+1:t3:

However, the code did not work exactly as proposed by you but you gave me the relevant hints how to proceed and now it works finde in Rules DSL. Here is my final working coding (in case that others search for the same solution in the fututre):

var timestamp = data.substring(start,ende) //timestamp as String extracted from raw data
var long resultsLong  = Integer.parseInt(timestamp) //timestamp as long integer
val instant = java.time.Instant.ofEpochSecond(resultsLong)
val tz = now.zone // default time zone
val final = ZonedDateTime.ofInstant(instant, tz)

For Debugging purposes I wrote the result of each line in OH log, which now correctly shows:

2022-10-20 21:36:44.575 [INFO ] [l.script.MemberUpdategpyicloud.rules] - timestamp: 1666294484
2022-10-20 21:36:44.575 [INFO ] [l.script.MemberUpdategpyicloud.rules] - resultsLong : 1666294484
2022-10-20 21:36:44.576 [INFO ] [l.script.MemberUpdategpyicloud.rules] - instant: 2022-10-20T19:34:44Z
2022-10-20 21:36:44.576 [INFO ] [l.script.MemberUpdategpyicloud.rules] - tz: Europe/Berlin
2022-10-20 21:36:44.576 [INFO ] [l.script.MemberUpdategpyicloud.rules] - final: 2022-10-20T21:34:44+02:00[Europe/Berlin]

Thanks to all for the great help!

1 Like