Handy Node-Red Date

While working on my thermostat I found myself repeating the same code all over the place – as I use function nodes for inline debugging and info – far more useful at times than the debug output.

I’ve now attached this simple code here to a function in my init page. I can use the global var “handyDate” all over the place as many times as required. This function is triggered by an inject node every second. I could have converted the timestamp info from the trigger but this is just as easy.

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? “0” : “”) + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? “0” : “”) + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? “0” : “”) + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? “0” : “”) + month;

    var day  = date.getDate();
    day = (day < 10 ? “0” : “”) + day;

global.set(“handyDate”,” at ” + hour + “:” + min + “:” + sec + ” on ” + day + “/” + month + “/” + year);

9 thoughts on “Handy Node-Red Date

  1. In the discussion here https://www.reddit.com/r/javascript/comments/20zx5n/why_doesnt_javascript_have_a_native_date/

    var d = new Date();

    var today = d.toJSON().replace(/(\d+)\-(\d+)-(\d+)T(\d+):(\d+):(\d+).*/, function (_, y, m, d, h, i, s) {
    return h + ‘:’ + i + ‘:’ + s + ‘ ‘ + m + ‘/’ + d + ‘/’ + y;
    });

    function formatDate(date, format) {
    date = date.toJSON().split(/[:/.TZ-]/);
    return format.replace(/[ymdhis]/g, function (letter) {
    return date[‘ymdhis’.indexOf(letter)];
    });
    }

    var today = formatDate(new Date(), ‘h:i:s m/d/y’);

  2. Peter.

    You could use dateformat.js from https://github.com/felixge/node-dateformat.

    – Download and popy it to ~/.node-red directory
    – Edit ~/.node-red/settings.js and inside

    functionGlobalContext: { }

    insert something like:

    functionGlobalContext: {
    df:require(‘./dateformat’),
    }

    – This is a demo flow:

    [{“id”:”d8b9867b.5d81d8″,”type”:”inject”,”z”:”1b9ff6dc.f03f39″,”name”:””,”topic”:””,”payload”:””,”payloadType”:”date”,”repeat”:””,”crontab”:””,”once”:false,”onceDelay”:0.1,”x”:280,”y”:280,”wires”:[[“70e9d368.2e9aec”]]},{“id”:”70e9d368.2e9aec”,”type”:”function”,”z”:”1b9ff6dc.f03f39″,”name”:”dateformat test”,”func”:”var now = new Date();\n\nvar dateFormat = global.get(‘df’);\n\n// Basic usage\nmsg.payload = dateFormat(now, \”dd/mm/yyyy hh:MM:ss\”);\n\nreturn msg;”,”outputs”:1,”noerr”:0,”x”:490,”y”:280,”wires”:[[“f44fb0ed.6fc94”]]},{“id”:”f44fb0ed.6fc94″,”type”:”debug”,”z”:”1b9ff6dc.f03f39″,”name”:””,”active”:true,”tosidebar”:true,”console”:false,”tostatus”:false,”complete”:”false”,”x”:710,”y”:280,”wires”:[]}]

    1. Got it, tested, but how would you slip the word “on” into this between date and time?

      msg.payload=dateFormat(“hh:mm:ss dddd, dd/mm/yy”);

      I tried without success.

      1. Just insert text into single quote. Something like this:

        msg.payload=dateFormat(“hh:mm:ss dddd, ‘ on ‘ dd/mm/yy”);

        You must use MM for minutes. mm is month and if you want 24 hours format use HH for hour.

  3. How about using built-in methods?

    date = new Date();

    var date_options = {year: ‘2-digit’, month: ‘2-digit’, day: ‘2-digit’ };
    var time_options = {hour: ‘2-digit’, minute: ‘2-digit’, second: ‘2-digit’ };

    global.set(“handyDate”,”at “+date.toLocaleTimeString(‘en-GB’, time_options)+” on “+date.toLocaleDateString(‘en-GB’, date_options));

  4. fmtDate(date, fmtStr) {
    let fmtFunc = {
    Y: function(d) { return d.getFullYear() },
    m: function(d) { return (‘0’ + (d.getMonth() + 1)).slice(-2) },
    d: function(d) { return (‘0’ + d.getDate()).slice(-2) },
    H: function(d) { return (‘0’ + d.getHours()).slice(-2) },
    i: function(d) { return (‘0’ + d.getMinutes()).slice(-2) }
    }
    //* if milliseconds – convert to date
    date = date instanceof Date ? date : new Date(date)
    return (fmtStr || ‘d.m.Y’).replace(/(Y|d|m|H|i)/g, (part) => fmtFunc[part](date))
    }

Comments are closed.