0
$(document).ready(function () {
    //Init
    var now = new Date();
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear() + "-" + (month) + "-" + (day);
    $('#PaymentDate').val(today);

});

I'm new to JavaScript So can someone help me. using this code I can get the current date...But, how can I add one month to this date and get the next month date.. Currently I'm getting this - 12/30/2020 (Today's Date) Add 1 month Means I want to get - 01/30/2021 (Next month date). Can you please integrate your solution/answer to this code and show

  • 1
    How do you plan to handle corner cases that appear at month end? What is *January 31st + 1 month*? – PM 77-1 Dec 30 '20 at 15:32
  • Define "one month" please. What's the expected result if today is the 31st and the next month has less than 31 days? Will people need to pay quicker in February, because the month is shorter? It might be easier and less ambiguous if you just add 30 days. – Olaf Kock Dec 30 '20 at 15:33

1 Answers1

2

Try this

$(document).ready(function () {
    //Init
    var now = new Date();

    // Add one month to the current date
    var next_month = new Date(now.setMonth(now.getMonth() + 1));
    
    // Manual date formatting
    var day = ("0" + next_month.getDate()).slice(-2);
    var month = ("0" + (next_month.getMonth() + 1)).slice(-2);
    var next_month_string = next_month.getFullYear() + "-" + (month) + "-" + (day);

    $('#PaymentDate').val(next_month_string);
});

You can also use this trick to get your YYYY-MM-DD style string instead of the manual formatting:

var next_month_string = next_month.toISOString().split('T')[0];
mandulaj
  • 733
  • 3
  • 10