Initializing a time type variable?


#1

1) Give a description of the problem
I want to create a start time with time variable. I want to initialize the variable to null and reset to null so I don’t need a boolean to determine if the start time is set.

2) What is the expected behavior?
I hope it can be set to null, but I don’t see information about it.

3) What is happening/not happening?
I am not sure how to debug this thing. I set to null and it does not error out.

The snapshot is the updated version that I don’t set null. However, the define time variables automatically commented for /* invalid date */. The snapshot does not show the comment but it’s in my code.


Thank you very much.


#2

Just curious as to why you need to set it to null when it will get overwritten by the set variable when your piston runs?


#3

I was thinking this way.

time starttime = null;
time endtime = null;

if(time period) {
turn on light;
set starttime = current time;
set endtime = null;
} else {
turn off light;
set endtime = current time;
if(starttime != null) {
calculate the total run time;
}

later after print out, reset everything back to null.

The reason I want the null value is because

Let’s say I run it in the in time period and I already turn the light on, the starttime is not set. However, it will set the endtime when the period is ended. The calculation will have endtime - starttime then it may error out since starttime is null.


#4

I don’t think there’s a way currently to do what you want as it defaults to $now when you log the value of an empty time variable.

As a workaround, if you’re interested, you can set up an ‘on event’ to catch the switch on/off outside of the automation.


How can I compare an empty/uninitialized datetime variable?
#5

You can set the time with an Expression rather than Value which allows more flexibility. You could use the value 0 which corresponds to midnight or 1 which corresponds to 1 millisecond after midnight. It looks like negative numbers throw an exception and numbers greater than the number of milliseconds in a day are a bit tougher to work with.


#6

Another option is to use integer as the type rather than time since you’re really just dealing with the duration here. That would allow you to use -1 as a not-set value that cannot possibly be a time. Note that setting an integer to null will just leave you with zero, so a negative value is better.


#7

Thank you all for all the information. It was a general question about if we can use null. My final approach is to compare a time after a time for the duration result.