ZonedDateTime - calculations

in OH2.5 I have some rule wich calculates my usage of water/gas etc. To grab the data from the database, I calculate some dates. After I have the correcte dates, I use .deltaSince fo find the correct values.

OH2.5 rule

//current month
val DateTime firstDayThisMonth = now.withDayOfMonth(1).withTimeAtStartOfDay()
//previous month
val DateTime firstDayPrevMonth = now.minusMonths(1).withDayOfMonth(1).withTimeAtStartOfDay()
val DateTime lastDayPrevMonth = firstDayThisMonth.minusSeconds(1)
//current month previous year
val DateTime firstDayThisMonthPrevYear = firstDayThisMonth.minusYears(1)
val DateTime lastDayThisMonthPrevYear = firstDayThisMonthPrevYear.dayOfMonth().withMaximumValue()
//previous month previous year
val DateTime firstDayPrevMonthPrevYear = firstDayPrevMonth.minusYears(1)
val DateTime lastDayPrevMonthPrevYear = firstDayPrevMonthPrevYear.dayOfMonth().withMaximumValue()

In OH3 I already converted some of them, but I can’t figure out how to get the last day of a month with ZonedDateTime. Maybe I’m making this to complicated and can this be simplified?

OH3 rule

//current month
val ZonedDateTime firstDayThisMonth = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0) 
//previous month
val ZonedDateTime firstDayPrevMonth = now.minusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0) 
val ZonedDateTime lastDayPrevMonth = firstDayThisMonth.minusSeconds(1)
//current month previous year
val ZonedDateTime firstDayThisMonthPrevYear = firstDayThisMonth.minusYears(1)
val ZonedDateTime lastDayThisMonthPrevYear = firstDayThisMonthPrevYear. ????
//previous month previous year
val ZonedDateTime firstDayPrevMonthPrevYear = firstDayPrevMonth.minusYears(1)
//val DateTime lastDayPrevMonthPrevYear = firstDayPrevMonthPrevYear. ???

withDayOfMonth(1).minusDays(1) gives you the last day of the preceding month.

1 Like

offcourse, stupid me… I almost do the same for lastDayPrevMonth.
Thanks for helping!

1 Like

ZoneDateTime offers no withDayOfWeek, is there another possibility to reach first day of current week in OH 3?

Was a bit tricky to get on the right path, now solved as follows:

val ZoneDateTime startOfThisWeek = ZonedDateTime.now(ZoneId.of("Europe/Berlin")).with(previousOrSame(DayOfWeek.of(1))).with(LocalTime.MIDNIGHT)
1 Like

Hello, can I also use it to determine the period since the last full hour?

For example, so that I can calculate the electricity consumption from a full hour?

val ZonedDateTime LastHour = now.minusMinutes(60)

takes the last 60 minutes since now