Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
How to increment value in the object Date each time by click event using JavaScript?

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.

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

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 class="change-date-button">Add three days</button>

about 4 years ago · Santiago Gelvez Denunciar

0

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

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda