Lelio Faieta
Lelio Faieta

Reputation: 6663

how to shift a date to the following month (fixed day)

I have a date in javascript that is dd/mm/yyyy format. I wanto to calculate from that date another date with the following requisites: month will be the following from the date chosen (january will shift to february, dicember to january and so on) year will shift accordingly day will be always 16

I am starting from this (ref. this question):

    var CurrentDate = new Date();
    CurrentDate.setMonth(CurrentDate.getMonth() + 1);
    console.log("Date after 1 months:", CurrentDate);

but need to set the day as 16 and to check that the edge situations are considered. Any suggestion on how to go on with this code?

P.S. i'm looking for a solution in Vanilla JS or jQuery with no additional libraries

Upvotes: 0

Views: 213

Answers (1)

hbamithkumara
hbamithkumara

Reputation: 2534

Try this..

function getDate16(d) {
  var date1 = d.split('/');
  var formattedDate1 =  date1[2] + '-' + date1[1] + '-' + date1[0] + 'T00:30:00.000Z';

  var CurrentDate = new Date(formattedDate1);
  CurrentDate.setDate(16);
  CurrentDate.setMonth(CurrentDate.getMonth() + 1);

  // Date formatting
  var date = CurrentDate.toISOString();
  var arr = date.substring(0, 10).split("-");
  date = arr[2] + '/' + arr[1] + '/' + arr[0];

  console.log("ISO format=", CurrentDate);
  console.log("dd/mm/yyyy format=", date);

}

getDate16("28/11/2019");
getDate16("31/12/2019");
getDate16("16/01/2020");

Upvotes: 2

Related Questions