DateTime issue again

if(now isAfter((LE_Sunset_Time.state as DateTimeType).calendar.timeInMillis) ||
   now.isBefore(LE_Sunrise_Time.state as DateTimeType).calendar.timeInMillis)

The first problem is to get the value of an Item you must call .state.

Secondly, the value of a DateTime Item is DateTimeType which is not the same thing as a Joda DateTime which now is. Therefore you can’t use it directly in the call to isBefore and isAfter. You must convert it into a format that Joda DateTime can understand.

Thirdly, as you are already guessing, Astro calculates the sunrise and sunset times at midnight. These times are absolute (i.e. include the date, not just the time of day). Therefore check if now is after sunset but before sunrise will never be true because the sunrise and sunset times you have are for today. For example, if it is after sunset and before midnight today, sunset time will be something like 19:31 2017/06/16 and your sunrise time will be something like 05:46 2017/06/16. In order for the if statement to evaluate to true you need the sunrise time for tomorrow or 05:47 2017/06/17.

But by using || instead of && you will get the behavior you want.

I recommend looking at the Time of Day Design Pattern for doing operations like these.

1 Like