Simple way to check if 'now' is before or after a certain time

Hi Folks!

When migrating from OH 2.5 to OH 3.0 I was fiddling around with datetime conversion in my rules. In OH 2.5 I used a lot of these time equations (with or without the minutes, mostly without because it’s easier and somewhat cleaner):

var Number hour = now.getHour

    if (hour < 22){
        if (HarmonyActivity.state != "PowerOff" && System_pod_mode.state == "avond"){
            Woonkamer_Preset.postUpdate(3)
        }
    }

So I thought of a sollution where I could just type the time in a variable / constant to define a certain point in time like: “09:33:00” and the code does the equation. It’s easier to read and more flexible. For instance, I can calculate the time easy by adding 93 minutes e.g. For my own code I didn’t had to use the date, so it’s using today’s date. None of my rules almost never use a day or date.

So I came up with this:

// here we could use a readable time, but we must use hours,minutes and seconds in 2 digits
    val String strTime1 = "09:11:50" 
// The date is extracted from today's date
    val String strDate = now.toLocalDateTime.toString.split("T").get(0) + "T" 
// Below we put it all together and create a zoneddatetime which Java understands
    val ZonedDateTime dteTime1 = ZonedDateTime.parse(strDate + strTime1 + ".000Z").withZoneSameLocal(ZoneId.systemDefault())

    if (now.isAfter(dteTime1) && now.isBefore(dteTime1.plusHours(1))){ // use it at your convenience
        logInfo("test.rules", "We're in the zone!")
    } else {
        logInfo("test.rules", "We're just not in the zone...")
    }

One thing which is strange: I have to extract 1 hour when I create the zoneddatetime. I think because of wintertime, not sure how this holds up when summertime begins… < maybe someone has a sollution for this?

I created this post so people can use it. It costs a lot of time (couple of hours) to think it all through if you’re not a programmer, was my experience.

1 Like

Could it be that “.000Z” is the reason for it ? .000Z makes the time UTC / GMT+0 timezone as far as I understand.

2 Likes

Yeah I thought of that but I can’t manage to change the timezone to +1. tried a lot of options like:

val ZonedDateTime dteTime1 = ZonedDateTime.parse(strDate + strTime1 + ".000+0100Z").withZoneSameInstant(ZoneId.systemDefault())

but it gives an error…

Maybe it also has something to do with: [ withZoneSameInstant(ZoneId.systemDefault()) ] but not sure how to change that to my timezone.

IMHO .withZoneSameInstant does change the TimeZone ONLY (without changing the hour/minute digits!!)
.withZoneSameLocal changes from the orginal TimeZone (“Z” or UTC) to your locally set zone.

2 Likes