[SOLVED] Rules: calculate difference between 2 DateTime in minutes


i have two items defined as below

DateTime mqtt_sensor_door_LastUpdate1        "1-Entry Door-Last  [%1$td/%1$tm %1$tH:%1$tM:%1$tS]" <clock>   (gChart,gHistory) 
DateTime mqtt_sensor_door_LastUpdate2        "2-Entry Door-Last  [%1$td/%1$tm %1$tH:%1$tM:%1$tS]" <clock> 

I want from a rule to get the difference in minute and Sec between mqtt_sensor_door_LastUpdate1 and DateTime mqtt_sensor_door_LastUpdate2

Please, Could someone assist?

Thanks in avance

Such code should give you the difference in seconds, calculation from there should be easy.

val Date1= new DateTime(( mqtt_sensor_door_LastUpdate1.state as DateTimeType).zonedDateTime.toInstant.toEpochMilli)
val Date2 = new DateTime(( mqtt_sensor_door_LastUpdate2.state as DateTimeType).zonedDateTime.toInstant.toEpochMilli)
var double diff = (Date2.millis - Date1.millis)/1000
1 Like



ZonedDateTime… until… ChronoUnit.TemporalUnit…

    import java.time.temporal.ChronoUnit
    val date_1 = Virtual_DateTime_1.getStateAs(DateTimeType).zonedDateTime
    val date_2 = Virtual_DateTime_2.getStateAs(DateTimeType).zonedDateTime
    val seconds_between = date_1.until(date_2, ChronoUnit.SECONDS)
    val minutes_between = date_1.until(date_2, ChronoUnit.MINUTES)
    val days_between = date_1.until(date_2, ChronoUnit.DAYS)
    val weeks_between = date_1.until(date_2, ChronoUnit.WEEKS)
    val months_between = date_1.until(date_2, ChronoUnit.MONTHS)
    val years_between = date_1.until(date_2, ChronoUnit.MONTHS)
    logWarn("Rules", "[{}], [{}]\nSeconds [{}]\nMinutes [{}]\nDays [{}]\nWeeks [{}]\nMonths [{}]\nYears [{}]", date_1, date_2, seconds_between, minutes_between, days_between, weeks_between, months_between, years_between)

Here’s another way to use ChronoUnit…


@5iver thanks it helped me a lot!

1 Like

Small bug:

should be
val years_between = date_1.until(date_2, ChronoUnit.YEARS)