Graceful way to convert DateTime to minutes in the day?

I’ve spent too much time fighting with this:

I’d like to be able to convert a dateTime item, such as dusk, to the minute of the day for use in a rule.

I’ve tried breaking out the hour and minute but I’m in Java number types hell, and figure there must be an easier way, but haven’t been able to get the right combination of search terms working to find an answer…

How are you getting this as DateTme? The astro binding?

Try ChronoUnit…

https://community.openhab.org/search?context=topic&context_id=93478&q=ChronoUnit%20order%3Alatest&skip_context=true

yes, as pulled from Postman:

{
    "link": "http://192.168.0.215:8080/rest/items/LocalSun_Set_StartTime",
    "state": "2020-02-23T17:23:00.000-0500",
    "stateDescription": {
        "pattern": "%1$tF %1$tR",
        "readOnly": true,
        "options": []
    },
    "editable": true,
    "type": "DateTime",
    "name": "LocalSun_Set_StartTime",
    "label": "SunSet_StartTime",
    "tags": [],
    "groupNames": []
}

LOL - clicked the link and the top result was my post! In my pre-caffeine state I was like ‘why the heck could I not find that last night’…

I’ll give this a try tonight. It looks like I need to create a midnight datetime to compare against?

1 Like

Shouldn’t you be able to just change the pattern format outputted?

I know how to do that for display purposes, but suspect I’ll be just as frustrated trying to coerce it into a number value I can use in a rule.

Soo aggravating… I’ve spent literally 3h going down different paths trying to get what should be a simple number to get.

I can get the hour and minute as numbers, but why can’t I multiply them?

rule "test rule 1"
when
    Item TestSwitchX changed
then
    val number astro_hour = (LocalSun_Set_StartTime.state as DateTimeType).format("%1$tH")
    val number astro_minute = (LocalSun_Set_StartTime.state as DateTimeType).format("%1$tM")
    val number dusk_minute = (astro_hour * 60) + astro_minute

    logInfo("test", dusk_minute)
end

returns this error:

Rule 'test rule 1': Unknown variable or command '*'; line 73, column 31, length 15

There are several issues in your rule. What are you trying to achieve? It looks like you are trying to get the number of minutes between midnight and sunset?

// add imports before global variables and rules
import java.time.temporal.ChronoUnit

rule "test rule 1"
when
    System started
then
    val sunset_zdt = civilDuskStart.getStateAs(DateTimeType).zonedDateTime
    val midnight_zdt = sunset_zdt.toLocalDate.atStartOfDay(sunset_zdt.getZone)
    val minutes_from_midnight = midnight_zdt.until(sunset_zdt, ChronoUnit.MINUTES)
    logInfo("Rules", "minutes between midnight and sunset: {}", minutes_from_midnight)
end
1 Like

oh, I have a number of issues beyond this rule!

But yes, that is what I am trying to achieve and your rule works perfect. Thanks for taking the time. I thought I was close last night…

1 Like