Convert ZonedDateTime to EpochSeconds

In the past I converted a datetime to epoch via this code:

val formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.'0000000Z'") //2023-05-12T12:00:00.0000000Z
var dateTimeFormatted = LocalDateTime.parse(time, formatter).atZone(ZoneId.systemDefault())  
val dateTimeEpoch = dateTimeFormatted.toEpochSecond

This is working fine, but I want to do the same in Blocky. I already have correct ZonedDateTime object, so I only need to conversion to EpochSeconds. How can I do that?

Blockly doesn’t have a block to get epoch. Most of the time there’s no reason to do that and the code can be much more readable and maintainable if you use the methods of the ZDT instead of messing with epoch.

It looks like your original string might be ISO8601 so all you should need to do is use “date time | text” block to convert the String to a ZonedDateTime. I just tried it and it worked for me.

You don’t say what you do with the epoch so :person_shrugging: If you want to find out how long it is between two ZDTs you have the “between” block.

image

If you want to see if a date time is before or after another one you have the “is before” block (which also supports after and equal). There is also an is between block.

Those are the most common things one might do with a DateTime and also the most common reason I’ve seen people use epoch.

2025-04-15 12:10:25.787 [INFO ] [openhab.automation.script.ui.blockly] - 2023-05-12T12:00Z
2025-04-15 12:10:25.789 [INFO ] [openhab.automation.script.ui.blockly] - true
2025-04-15 12:10:25.790 [INFO ] [openhab.automation.script.ui.blockly] - 704

But in the unlikely event this isn’t an XY Problem and you are using epoch for something exotic, you’ll have to use the “inline script” block to extract epoch and assign it to a variable. However, if you are doing something exotic like that, Blockly is unlikely to be the best tool for the job.

image

myEpoch = time.Instant.from(myDateTime).epochSecond()

Assumes you’ve created “myEpoch” in the usual way.

Thanks for your answer!

A week ago, I created a new item and I forgot to set persistence for this item to my influxdb. So I wanted to add the states to InfluxDB by reading them from RRD4j. I have another rule where I also add values, which are coming from outside OH, to InfluxDB and there I used epoch to define the date/time.

But I found a different way to do this in Blocky (not sure if this is the perfect way, but it worked :))

Which library adds this block? Looks interesting.

None. It’s a standardv OH block you’ll find under Run and Process.