Adding variables

I am trying to convert time to total minutes. The result is always 601 instead of 61. What am I doing wrong?

thanks!

global.set(msg.topic,msg.payload);
var hour = global.get("timehour");
var minute = global.get("timeminute");
var tottime = (hour*60)+minute;
if (hour!==undefined && minute!==undefined) {
var mytime = new Date();
mytime.setHours(hour, minute, 0);
mytime.setMilliseconds(0);
mytime.setFullYear(2000,01,01);
global.set("start",mytime.getTime());
}
msg.payload = tottime;
return msg;

What values are in those globals? Look in the context browser on the sidebar (where debug output normally is)

Also, you are setting tottime before checking the variables.

What I often do to debug these situations is instead of creating temp vars, put everything in msg the put a debug node after the function node (debug node set to output "complete object")

E.g.

global.set(msg.topic,msg.payload);
msg.hour = global.get("timehour");
msg.minute = global.get("timeminute");
var tottime = (msg.hour*60)+msg.minute;
if (msg.hour!==undefined && msg.minute!==undefined) {
var mytime = new Date();
mytime.setHours(hour, minute, 0);
mytime.setMilliseconds(0);
mytime.setFullYear(2000,01,01);
global.set("start",mytime.getTime());
msg.mytime = mytime;
}
msg.payload = tottime;
return msg;

Now when the function node outputs a msg, you can inspect the values it used to compute tottime.

The most likely explanation for that resulting in 601 rather than 61 is that minute is a String and not a number. This means it is joining the strings together 60+"1" = "601" rather than handling both as numbers and adding them as you would expect.

That is where Steve's suggestion comes in - using the context sidebar you can confirm their types (ie, are they displayed with surounding "quotes" to indicate they are strings).

The quick fix is to use parseInt() (assuming they are integers and not floats) to convert the String to a number.

msg.hour = parseInt(global.get("timehour"));
msg.minute = parseInt(global.get("timeminute"));

But you may want to consider looking at where you are storing those values and whether you want to convert them to numbers before storing them instead.

Thanks for the feedback you were right about the "string". This is what works! Learning everyday.

global.set(msg.topic,msg.payload);
var hour = global.get("timehour");
var minute = global.get("timeminute");
if (hour!==undefined && minute!==undefined) {
var mytime = new Date();
mytime.setHours(hour, minute, 0);
mytime.setMilliseconds(0);
mytime.setFullYear(2000,01,01);
global.set("start",mytime.getTime());
}
msg.hour = parseInt(global.get("timehour"));
msg.minute = parseInt(global.get("timeminute"));
msg.payload = (msg.hour*60)+msg.minute;
return msg;