How to shift or move date by `{n}` number of days

How to shift or move date by `{n}` number of days

Here is a quick way to shift a day by a few days, by adding those days, and adjusting the date. In the process, we will pay attention on moving the days into another month or year if we have to.

Of course, this depends on the few date manipulation methods we saw last time in our blog. On top of that, we will also use getDate and setDate methods. Again, our aim is to write a simple utility function to move data into the future or the past using n number of days.

function shiftDate(n, date=null) {
    return date? new Date(date) : new Date();
}

First, our function accepts two parameters, the number of days it has to be shifted to and the date. Note that the date is optional. And that enables us to just shift the current date by n number of days. Then, we convert the provided date, which was a string, into a Date object. Again, if the second parameter is not provided then we just use new Date() to get the current date.

Using the setDate and getDate instance methods

After that, we are in a good position to use the instance methods of Date object. In this case, we will use the getDate and setDate methods. The getDate function gets the number of days in a month. Whereas, the setDate adds a given number into the time stamp of our date object. Hence, we can do date.setDate(date.getDate() + n).

function shiftDate(n, date=null) {
    const myDate = date? new Date(date) : new Date()
    return myDate.setDate(myDate.getDate() + n)
}

At this point, our date object is a timestamp with the n days added to it. What we want to do next is to convert it into a human-readable format. For that purpose, we can use toLocaleDateString instance method.

function shiftDate(n, date=null) {
    const myDate = date? new Date(date) : new Date()
    myDate.setDate(myDate.getDate() + n)
    return myDate.toLocaleDateString()
}

Our date shifting function in action

Now, we are done with our utility function. We can use our utility function to travel either to the future or the past. Here are some examples:-

console.log(shiftDate(8))//Move eight days into the future from now.
console.log(shiftDate('14/05/2020', 14))
console.log(shiftDate('02/05/2012', -4)) //Move 4 days into the past

Summary

We want to build a utility function to go back in time or to go to the future. We used the getDate() and setDate() instance methods.