Get sum of all historical data from last month in JS

Hello, how do I get a sum of all historical data from last month…means from 1.3-31.3 but also from 1.4-30.4?

This is how I get the first of a month:

val startDate = now.minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0)

But How do Iget the last day of month?

hi,

the following rule I run monthly on the 1st at 00:00 to determine the power consumption for a device for 1 month.

rules.JSRule({
    name: "Stromverbrauch Entfeuchter Vormonat",
    description: "Ermittelt Stromverbrauch des Entfeucheters vom Vormonat - " + rules_filename + ".js",
    triggers: [triggers.GenericCronTrigger("0 0 0 * 1/1 ?")],  // monatlich am 1. um Mitternacht
    execute: event => {

        var MeterUse = Quantity('0.0 kWh');

        MeterUse = items.ZWaveNode2_PowerNode_ElectricMeterkwH_Day.history.sumSince(time.ZonedDateTime.now().minusDays(time.ZonedDateTime.now().dayOfMonth()));
        items.getItem("ZWaveNode2_PowerNode_ElectricMeterkwH_Month").postUpdate(MeterUse);
        logger.info("Stromverbrauch Entfeuchter vergangenes Monat: " + MeterUse + " kWh");
    }
});
1 Like

quite the same as startDate:

val startDate = now.minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0)
val endDate = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0)

Please keep in mind, that a value with timestamp 2023-04-01 00:00:00.001 will not be used, as it’s out of bounds. So it’s really that simple.