Finding date by subtracting X number of days from a particular date in Javascript

后端 未结 9 1958
滥情空心
滥情空心 2020-11-27 05:21

I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other i

9条回答
  •  北海茫月
    2020-11-27 06:01

    I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.

    function dateManipulation(date, days, hrs, mins, operator) {
        date = new Date(date);
        if (operator == "-") {
           var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
           var newDate = new Date(date.getTime() - durationInMs);
        } else {
           var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
           var newDate = new Date(date.getTime() + durationInMs);
        }
       return newDate;
    }
    

    Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.

    var today = new Date();
    var newDate = dateManipulation(today, 3, 0, 0, "-");
    

提交回复
热议问题