Subtract or add hours to a date

May 18, 2020 • edited May 19, 2020

We have all seen you obliged to save the date / time of a transaction. For security, it is preferable to make this calculation in the back-end, but if security is not so important, here is the tool you need to subtract or add hours or days to the current date.

First the following function, which will allow us to show the hours, minutes or days of the date with two characters instead of one:

Number.prototype.double = function ()
{
    var nm = this.toString();
    return (nm == '0') ? nm : ((nm.length < 2) ? '0' + nm : nm);
};

Number(0).double(); // RESPUESTA: '0'
Number(3).double(); // RESPUESTA: '03'
(32).double(); // RESPUESTA: '32'
(589).double(); // RESPUESTA: '589'

var n = 47;
n.double(); // RESPUESTA: '47'

OK, now what we came to:

function xDateTime (cnf)
{
    var cnf = cnf || {};
    var dte = new Date();
    var dteD = dte.getDate()
    var dteM = dte.getMonth() + 1;
    var dteY = dte.getFullYear();
    var tme = dte.getTime()
    var nDte = dte.setTime(parseInt(tme + parseInt((cnf.hours ? cnf.hours : 0) * 60 * 60 * 1000)));

    dteD = dte.getDate().double(); 
    dteM = dte.getMonth() + 1; 
    dteY = dte.getFullYear();

    var tmeH = (dte.getHours() >= 12 ? dte.getHours()-12 : dte.getHours()).double();
    var tmeM = dte.getMinutes().double()
    var tmeS = dte.getSeconds().double();

    var rtn = '';
    var rtnD = dteD + '/' + dteM + '/' + dteY;
    var rtnT = tmeH + ':' + tmeM + ':' + tmeS + (dte.getHours() >= 12 ? 'PM' : 'AM');

    switch (cnf.type)
    {
        case 'd':
            rtn = rtnD;
            break;
        case 't':
            rtn = rtnT;
            break;
        case 'dt':
            rtn = rtnD + ' ' + rtnT;
            break;
        case 'td':
            rtn = rtnT + ' ' + rtnD;
            break;
        default:
            rtn = rtnD + ' ' + rtnT;
    };

    return rtn;
};

To receive the time or date, we apply as follows:

xDateTime();
xDateTime({ type: 'd' });
xDateTime({ type: 't' });
xDateTime({ type: 'dt' });
xDateTime({ type: 'td' });

If we need the function to return an early date or time, we apply the number of hours that we need to advance:

xDateTime({ hours: 5 });
xDateTime({ hours: 12 });
xDateTime({ hours: 24 });
xDateTime({ hours: 36 });
xDateTime({ hours: 48 });

Similar with a late date:

xDateTime({ hours: -24 });
xDateTime({ hours: -36 });
xDateTime({ hours: -48 });

Combining both parameters:

xDateTime({ type: 't', hours: 5 });
xDateTime({ type: 'd', hours: -36 });
xDateTime({ type: 'd', hours: -48 });
xDateTime({ type: 'dt', hours: 24 });
JavaScript

Junihh

Junihh is talk about web-dev and opinion.

Spam, the curse we can regulate

Templates for lists without templates engines