Home > Back-end >  How to increment value in the object Date each time by click event using JavaScript?
How to increment value in the object Date each time by click event using JavaScript?

Time:07-16

I wanna change the date object every time when I'm clicking the button. I'm trying to handle it using the following function:

.on('click', '.change-date-button', function () {
    Date.prototype.addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate()   days);
        return date;
    }
    var date = new Date();
    console.log(date.addDays(3));
}

But as result, I get the same object. How to increment and decrement the date object in the correct way and get a new date added seven days every time by click? As an example, I get 18/07/2022 several times, however, I need to get 21/07/2022, 24/07/22, etc... by the next click.

CodePudding user response:

It is a bad idea to redefine a method on a prototype at each click of a button. You might as well just do the job inline -- without any function.

Also, your function explicitly does the job of not changing the date, but returning a new one, and the function is always called with today's date and time -- at every click.

You refer to "the date object" as a global object, but then you need to create it as a global:

var date = new Date(); // <-- outside handler scope
// ...

$(document).on('click', '.change-date-button', function () {
    date.setDate(date.getDate()   3);
    console.log(date);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >Add three days</button>

CodePudding user response:

An alternative is to use the date-fns library, because in this case you wouldn't need to redo something that already exists in a simplified way.

https://date-fns.org/v2.28.0/docs/add

  • Related