Migrate rule to OH3 to calculate days between two DateTime

Hi,
right now, I’m migrating my OH2.5 setup to OH3. Until now, I was able to migrate all may things and items. But now I got stuck on rule, which provides me the days until next garbage collection.
The line of the rule in OH 2, I’m not able to migrate looks like this:

if	(Abfall_Datum_Schwarz.state.toString != "UNDEF") {
Tage_schwarzeTonne = Math::round(Math::ceil((Abfall_Datum_Schwarz.state.toString.millis - LocalDateTime.now()) / 86400000.0))}
else {Tage_schwarzeTonne = 999}

It should calculate the days between today and the date “Abfall_Datum_Schwarz”, which comes from icalendar binding and is from type DateTime.
I know, that in OH 3, I have to use Java zoned DateTime instead of Joda time. I tried to fix the lines with what I found on the internet about Java zoned time. Unfortunately, I had no success. Does anybody have a hint for me, what I have to change?

The hint is to use Duration.between: :slight_smile:

Search results for 'duration.between' - openHAB Community

1 Like

Thanks for your help! It took some time to find out how to convert the item.state to zoned DateTime, but now it works. My code looks now like this:

if	(Abfall_Datum_Schwarz.state.toString != "UNDEF") {
Tage_schwarzeTonne = Duration.between(now, (Abfall_Datum_Schwarz.state as DateTimeType).zonedDateTime).toDays() + 1}
else {Tage_schwarzeTonne = 999}

Maybe it is helpful for somebody else.

4 Likes

After running in trouble because of Item-State NULL and the Duration didnt go to 0, when both dates were the same, is optimized my rule. Now it looks like this:

if	(Abfall_Datum_Schwarz.state instanceof DateTimeType) {
Tage_schwarzeTonne = Duration.between(now, (Abfall_Datum_Schwarz.state as DateTimeType).zonedDateTime.plusHours(23)).toDays()}
else {Tage_schwarzeTonne =  999}
1 Like