JavaScript: how to create a date in the past

JavaScript: how to create a date in the past

In this article we will see how to create a date in the past with JavaScript.

In this article we will see how to create a date in the past with JavaScript.

We can create a function that takes as an argument the number of days to subtract from the current date. Then we use the getDate() and setDate() methods to get the day of the month (an integer) and then perform the subtraction operation.


'use strict';

const daysAgo = (numberOfDays = 1) => {
    if(typeof numberOfDays !== 'number') {
        numberOfDays = 1;
    }
    const currentDate = new Date();
    return currentDate.setDate(currentDate.getDate() - Math.abs(numberOfDays));
};