Set context array not working

I get this

date isobject: Wed Jul 03 2019 11:00:32 GMT+0200 (CEST)
typeof a is object

I don't see in the docs for javascript new Date() where it says you can pass it an object.

And what exactly doesn't work?

function GetTime (date){
    var a = new Date(date);
    node.warn("date is" + typeof date +": "+ date);
    node.warn("typeof a is " + typeof a );
    node.error(a);
    h = a.getHours();
    m = a.getMinutes();
    s = a.getSeconds();
    var t = [h,m,s];
    return t;
}

This, I can't get it to work... I get TypeError: Cannot set property '0' of undefined

As I said, I can't see in the docs for new Date() where it says you can pass it an object.

That error does not come out of that function. You are not trying to set a property called 0 in that code. It must be coming from somewhere else in your function.

Looking through your code, I can see you have this for loop:

        for(j = 0; j < StartDiff.length; j++){
            timeDef[j] = EndDiff[j] - StartDiff[j];
        }

But you have not defined timeDef anywhere. You do have var timeDef at the top, but it isn't initialised to anything - so will be undefined. That would certainly be one cause of the error.

But stepping back from that, it looks like you are trying to calculate the different between a start time and an end time.

Your code turns a Date object into an array [hh,mm,ss] and then it calculates the different between each of those individual values and joins them into a single string.

That is not going to give you a value that you can use.

If the start time is 12:34:56 and the end time is 13:21:50, you will end up with the arrays [12,34,56] and [13,21,50]. When you calculate timeDef you will get [1,-13,-6]. When you join those into a string, you'll get "1-13-6" which is pretty meaningless.

To calculate time differences, don't try to split it up like that.

Given startTime and endTime as Date objects, a much better way to calculate the difference is to do:

var diff = endTime.getTime() - startTime.getTime();

That will return the number of milliseconds between the two times. You can then do some simple maths to convert that into hours/minutes/seconds if you really want to.

1 Like