Calculate the difference between 1st january 00:00 actual year and now

hi !

how can i caclulate the difference in persitent data beween the absulute beginnin of the year and the actual time&date ? im usian actual release on ubuntu

Ciao Gerd

Depends on which rule language you use.

In javascript you could get the difference like this:

var yearStart = time.toZDT('00:00:00').withMonth(1).withDayOfMonth(1);
var diff = items.YourItemName.persistence.deltaSince(yearStart);

With this you get the PersistedState object, as you can see in doc here JavaScript Scripting - Automation | openHAB

From PersistedState you can get value as string, number or Quantity:

diff.state(); // as string (with unit, if the item has one)
diff.numericState(); // numeric state (in Item's unit, if the item has one)
diff.quantityState(); // Quantity object allowing you to convert and compare between different units

Hi !
I use java but somehow my rule doesnt work

rule “Save yearly consumption em3”
when
Item SP3em_consum changed
or
Time cron “0 0 0 * * ?” //
then
var yearStart = time.toZDT(‘00:00:00’).withMonth(1).withDayOfMonth(1);
var diff = items.SP3em_consum.persistence.deltaSince(yearStart);
SP3em_con_actual_year.sendCommand(diff)
end

and openhab log puts out a lot of errormessages
like
2025-02-19 15:56:15.395 [ERROR] [.handler.AbstractScriptModuleHandler] - Script execution of rule with UID ‘shelly.3em-5’ failed: The name ‘time’ cannot be resolved to an item or type; line 86, column 21, length 4 in shelly.3em

the related items are configured as numbers

Ciao Gerd

That’s not Java but Rules DSL, though Rules DSL does use Java classes here and there.

And that’s not code fences. Please use

```
code goes here
```

None of that will work in Rules DSL. You’ll have to use Rules DSL syntax and Rules DSL and Java classes in a Rules DSL rule. You can’t just paste JS into some other programming language and expect it to work.

rule “Save yearly consumption em3”
when
    Item SP3em_consum changed
    or
    Time cron “0 0 0 * * ?” //
then
    // see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html
    var yearStart =  now.withMonth(1).withDay(1).withHour(0).withMinute(0).withSecond(0).withNano(0)
    // see https://www.openhab.org/docs/configuration/persistence.html#persistence-extensions-in-scripts-and-rules
    var diff = SP3em_consum.deltaSince(yearStart)
    // should be postUpdate, see https://www.openhab.org/docs/configuration/rules-dsl.html#manipulating-item-states
    SP3em_con_actual_year.postUpdate(diff)
end

OK Clear so far , but still a failure in log

2025-02-19 23:02:37.073 [ERROR] [.handler.AbstractScriptModuleHandler] - Script execution of rule with UID ‘shelly.3em-5’ failed: ‘withDay’ is not a member of ‘java.time.ZonedDateTime’; line 87, column 23, length 27 in shelly.3em

Ciao Gerd

Try withDayOfMonth(1)

Hi !

Ok this works… persistence was missing

var diff = SP3em_consum.deltaSince(yearStart,“rrd4j”)

Ciao Gerd