DateTime Conversion (openHAB 2.x)

I’ll have to go through all the cases in the OP. It’s on my list of todos. There shouldn’t be too many changes though. Most of the commonly used stuff is the same between the two.

Potentially nothing. There are a few little cases though where you might run into exceptions. I don’t have a list of all errors I would expect you’ll see at this time though.

None. Joda is totally gone and is completely replaced by native Java time classes. However, now is still there and has the plusSeconds et al functions so it should be mostly transparent for you.

plusMinutes should definitely work without change. I’m not 100% positive about withTimeAtStartOfDay. But

now.withHour(0).withMinute(0).withSecond(0)

should be the equivalent. Here is the full JavaDoc for the class.

1 Like

Thanks Rich.
A silly(?) question: how can I use the future Java code in OH2 today rather than Joda ?

now.withHour(0).withMinute(0).withSecond(0)

on current OH 2 (but running Java 11) gives me

2020-10-26 17:54:31.530 [ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'sage für den Rest des Tages erwartete Strommenge voraus': 'withHour' is not a member of 'org.joda.time.DateTime'; line 309, column 9, length 15

I think you need to do the following.

import java.time.ZonedDateTime

...

    // in a Rule
    val now = ZonedDateTime::now

Note, you can’t use a ZonedDateTime as the time in createTimer in OH 2. You still have to use Joda DateTime for that.

There is an easier way to do this. If you have a ZonedDateTime you can easily update the time using one of the LocalTime constants:

    ZonedDateTime.now().with(LocalTime.MAX)
    ZonedDateTime.now().with(LocalTime.MIDNIGHT)
    ZonedDateTime.now().with(LocalTime.MIN)
    ZonedDateTime.now().with(LocalTime.NOON)

You can already replace Joda-Time in your OH 2.5 rules today with java.time. That’s how I did it and have no issues with time when using the same rules in OH 3.

1 Like

Are you sure?

When I add this to a rule:

import java.time.ZonedDateTime

		//val startOfDay = now.withTimeAtStartOfDay
		val startOfDay = ZonedDateTime.now().with(LocalTime.MIDNIGHT)

… then it errors in VSCode with Type mismatch: cannot convert from LocalTime to TemporalAdjuster.

It might work better if you also:

import java.time.LocalTime

1 Like

I also could not get that one to work either.

Do you rather mean to import java.time ?

And mind we’re in rules DSL so I think I cannot do ZonedDateTime.now() that’s giving errors.
Need to use ZonedDateTime::now. Same likely for the MIDNIGHT literal but no matter what I try it doesn’t work.