Date shift in JavaScript

Date shift in JavaScript can be done by counting days of the month and thinking of 28 or 29 days in February. Don’t forget the year. This is a long and complicated algorithm. I suggest a simpler solution. Transform date to the number of milliseconds, and make easy arithmetic with integers. After addition and subtraction, create date from the milliseconds.

<< < > >>

In this example, shifDate is called on the onClick event with parameter -1 and 1 for the day shift, and -7 and 7 for the week shift. With a few lines of JavaScript, date can be shifted easily.

function shiftDate(shift) {
    // set reference to the element containing date
    var txtDate = document.getElementById('txtDate'),
        // extract month, day and year from the txtDate string (format is mm/dd/yyyy)
        mm = txtDate.innerHTML.substring(0, 2),
        dd = txtDate.innerHTML.substring(3, 5),
        yyyy = txtDate.innerHTML.substring(6, 10),
        // convert txtDate to the miliseconds (mm-1 because months start with 0)
        mSeconds = (new Date(yyyy, mm - 1, dd)).getTime(),
        // initialize date object
        objDate = new Date();
    // set shifted date (86400000 is the number of miliseconds in one day)
    objDate.setTime(mSeconds + 86400000 * shift);
    // get month, day and year from shifted date (reuse mm, dd and yyyy variables)
    mm   = objDate.getMonth() + 1;
    dd   = objDate.getDate();
    yyyy = objDate.getFullYear();
    // set leading zero if needed
    if (mm < 10) {
        mm = "0" + mm;
    if (dd < 10) {
        dd = "0" + dd;
    // write back shifted date to the HTML element
    txtDate.innerHTML = mm + '/' + dd + '/' + yyyy;

Just for a note, current date is displayed using another JavaScript code. I had to use client side logic, because this is a classic WordPress post.

2 thoughts on “Date shift in JavaScript

  1. Some genuinely great information, Glad I discovered this. Good teaching is onefourth preparation and threefourths theater. by Gail.

Leave a Comment