Error- subtract().

Hi, I'm creating a time function in the new SDK and I'm getting an error in this line:

if(new Time.Moment(Time.now().value()).subtract(lastRunTime).value() < new Time.Duration(5 * 60).value()) {

Where is the error and how to fix it?

Thank you

Top Replies

All Replies

  • Not sure without seeing the definition of lastRunTime. I assume it's supposed to be a Moment?

    The following code compiles and runs for me without error:

    var lastRunTime = Time.now();
    var test = new Time.Moment(Time.now().value()).subtract(lastRunTime).value() < new Time.Duration(5 * 60).value();

    Also, you can simplify your code quite a bit:

    if (Time.now().value() - lastRunTime.value() < 5 * 60) {

  • Hi here is the full code for idea:

    if(Toybox.System has :ServiceDelegate) {
        		if(Application.getApp().getProperty("WeatherUpdated") == null) {
        			var lastRunTime = Background.getLastTemporalEventTime();
        			
    				if(new Time.Moment(Time.now().value()).subtract(lastRunTime).value() < new Time.Duration(5 * 60).value()) {
    				    var nextRunTime = lastRunTime.add(new Time.Duration(5 * 60));
    				    
    				    Background.registerForTemporalEvent(nextRunTime);
    				} else {
    				    var fiveSecondsFromNow = new Time.Moment(Time.now().value());
        			
    	    			fiveSecondsFromNow.add(new Time.Duration(5));
    	    			
    	    			Background.registerForTemporalEvent(fiveSecondsFromNow);
    				}
        		} else {
        			Background.registerForTemporalEvent(new Time.Duration(Application.getApp().getProperty("refresh_rate") * 60));
    		var view = new $.WeatherView();
            var delegate = new $.SampleDelegate();
            return [view, delegate] as Array<Views or InputDelegates>;
        }
    	 }
    	  }
    

    Thank you

  • The problem is that getLastTemporalEventTime() can return a Moment or null. The type checker will flag that as an error, because the code would crash at runtime in the event lastRunTime is null (Moment.subtract() doesn't accept null as an argument).

    The fix is to change your if-statement to add a null check.

    e.g.

    if (lastRunTime != null && new Time.Moment(Time.now().value()).subtract(lastRunTime).value() < new Time.Duration(5 * 60).value()) {

    or

    if (lastRunTime != null && Time.now().value() - lastRunTime.value() < 5 * 60) {

  • Thank you very much for the explanation and help.Wink