Days left from date to date

Hi

I´m struggling with my function node.
collection data from an API, get dates in this format: "2021-04-19T00:00:00"
I would like to take the date from today, and show remaining days to the date from the api.

tried various of different combinations, but only get "NaN" in the debug window.

here are my code snippet:

var d = new Date();
var diff = Math.round((d - msg.payload.date));
msg = {payload:diff};
return msg;

Also tried this:

var d = new Date();
var daysLeft;
daysLeft = Math.floor((d-msg.payload.date)/(1000*60*60*24));

msg = { payload:daysLeft};
return msg;

kind of hit the wall here.
any good suggestions?

Regards,
Anders

Off the top of my head

const apiDt = new Date("2021-04-19T00:00:00")
const nowDt = new Date()

const diff = apiDt - nowDt

Should result in a number of milliseconds. That should be fairly easy to convert.


Not terribly efficient:

[{"id":"5509f63c.303728","type":"inject","z":"ef122f0d.d488b","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":170,"y":200,"wires":[["a35c299b.3731f8"]]},{"id":"a35c299b.3731f8","type":"function","z":"ef122f0d.d488b","name":"","func":"const apiDt = new Date(\"2021-04-19T00:00:00\")\nconst nowDt = new Date()\nconst diff  = apiDt - nowDt\n\nmsg.payload = {\n    \"millisec\": diff,\n    \"sec\": diff / 1000,\n    \"minutes\": diff / (1000*60),\n    \"hours\": diff / (1000*60*60),\n    \"days\": diff / (1000*60*60*24),\n    \"weeks\": diff / (1000*60*60*24*7),\n}\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":340,"y":200,"wires":[["94a7aec6.4f6d1"]]},{"id":"94a7aec6.4f6d1","type":"debug","z":"ef122f0d.d488b","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":530,"y":200,"wires":[]}]
const apiDt = new Date("2021-04-19T00:00:00")
const nowDt = new Date()
const diff  = apiDt - nowDt

msg.payload = {
    "millisec": diff,
    "sec": diff / 1000,
    "minutes": diff / (1000*60),
    "hours": diff / (1000*60*60),
    "days": diff / (1000*60*60*24),
    "weeks": diff / (1000*60*60*24*7),
}

return msg;
{
   "millisec":3376114685,
   "sec":3376114.685,
   "minutes":56268.578083333334,
   "hours":937.8096347222222,
   "days":39.07540144675926,
   "weeks":5.582200206679894
}

Hi and thanks for a fast reply :slight_smile:
I need to take the apiDt from the msg.payload.date object.
Can I use that directly like the quote below?

You certainly can as long as you are sure that property will exist.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.