Add a month to jQuery

Asked

Viewed 245 times

1

I have the following date:

2017-12-22 (22 December 2017);

You would need an increment that adds up to 1 month to the current one, returning:

2018-01-22 (22 January 2018).

How do I do it in jQuery?

  • 2

    Need to be in jquery? With pure javascript you make it easy.

2 answers

6


var date = new Date();
console.log(date); // "2017-10-04T20:36:17.560Z"
date.setMonth(date.getMonth() + 1);
console.log(date); // "2017-11-04T21:36:17.560Z"

Uses the .getMonth() to know the date month, and then use the .setMonth() to change the month.

Then to show formatted can be for example like this:

var date = new Date();
console.log(date); // "2017-10-04T20:36:17.560Z"
date.setMonth(date.getMonth() + 1);
console.log(date); // "2017-11-04T21:36:17.560Z"

var formatadoA = date.toLocaleDateString('pt-BR');
console.log(formatadoA); // dá 04/11/2017

var formatadoB = [
  date.getDate(), date.getMonth() + 1, date.getFullYear()
].map(nr => nr < 10 ? '0' + nr : nr).join('-');
console.log(formatadoB); // dá 04-11-2017

  • He returned Sat Nov 04 2017 17:53:06 GMT-0200 (Brazilian daylight saving time) - https://s1.postimg.org/1y7pntf07j/1111.png All the way I wanted, but how do I format this data as follows: "04-11-2017";

  • @Webcraft can use different ways. I joined two variants to the answer.

  • Thank you very much. I am beginner, but I managed to understand your code perfectly. :)

0

If only to add the month can be done as follows on the link

function calcularMes(){
    var dataIncial = $('#checkin').val();
    var dataArray = dataIncial.split('/');
    var dia = dataArray[0];
    var mes = parseInt(dataArray[1]) + 1;
    var ano = dataArray[2];

    var novaData = dia + "/"+ mes + "/"+ano;
    $('#checkout').val( novaData );

}

https://jsfiddle.net/cbcarlos/0rj21xsq/

  • The code in the fiddle would look better as an executable snippet directly in the answer. It becomes more practical to anyone who is seeing the read and code response and runs it. As it is it ends up having nothing in the answer other than the link itself.

  • I tried to snippet directly into the reply, but some libraries didn’t work, so I added by jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.