Compare DateTime to Static DateTime

Soo guys i need your help,

i want to compare two DateTimes with each other. So far so good.

if ( datemorning.isBefore((Sunrise_Time.state as DateTimeType).calendar.timeInMillis) ) {
        executeCommandLine("/etc/openhab2/scripts/ on")
        postUpdate(FUNKD, "ON")

The problem is that datemorning needs to be a static DateTime of “06:00”.
Sure i could define a DateTime in the items file and call it with DateMorning.state but this is not the way i want to code this.

I’ve tried quite a few tricks but none of them worked.

For example:

val SimpleDateFormat sdf = new SimpleDateFormat("HH:mm")
val String timestampString = sdf.format("06:00")
val DateTimeType datemorning = DateTimeType.valueOf(timestampString)


var DateTime datemorning = new DateTime(( "06:00" as DateTimeType).calendar.timeInMillis)


SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm")
Date date = parseFormat.parse("06:00")

I only need the hours and minutes (“HH:mm”). No month or year!

So is there any way to cast the DateTime without to recall the state of an already existing DateTime in the items??

Usually, we have to code things the way the language supports regardless of what we want.

DateTimeType and DateTime objects are absolute. They are a specific time on a specific date. You cannot define a DateTime or DateTimeType for “06:00” because there is no date. It is called DateTime for a reason. You HAVE to have the date part.

Every time this Rule runs you will have to get the time for 06:00 for today.

See Design Pattern: Time Of Day

    val long morning_start   = now.withTimeAtStartOfDay.plusHours(6).millis
    if((Sunrise_Time.state as DateTimeType).getZonedDateTime.toInstant.toEpochMilli > morning_start) {

Thank you for the quick response.

I did not know that the DateTime need to be an actual date and can’t exist without month etc.

I’ll test the new code soon and inform you about the outcome.

Sooo i just tested it … worked exactly the way i wanted it to.

Thanks for your help!

1 Like