0

I have an HTML file and it has a field to input the date and this html file is interacting with a JavaScript file.

So, what i want to do is as soon as i enter the date input it should get converted to the first date of next month.

for example: if I am providing the date input as 21/05/2020 (dd/mm/yyyy format) it should get converted to 01/06/2020 (dd/mm/yyyy format) i.e, first date of next month.

can anyone help with the JavaScript logic to do this?

Vinay
  • 1
  • 2

3 Answers3

2

Just increment the month by 1, and set the date to 1:

document.getElementById('demo').addEventListener('blur', function({target}) {
    const { value } = target;
    const d = new Date(value);
    d.setMonth(d.getMonth() + 1)
    d.setDate(1);   
    const date = d.toLocaleDateString('en-US', {
        year: 'numeric',
        month: "2-digit",
        day: "2-digit"
    });
    console.log(date)
    const [month, day, year] = date.split('/');
    target.value = [year, month, day].join('-');
});
<input type="date" id="demo"/>
dave
  • 62,300
  • 5
  • 72
  • 93
0

Use moment library

moment('21/05/2020', "dd/mm/yyyy").add(1, 'M').startOf("month")
aaditya
  • 555
  • 7
  • 19
0

Below is the plain JS implementation.

const d = new Date("05/21/2020")

const firstDayOfNextMonth = (str) => {
  const d = new Date(str)
  const month = d.getMonth()

  d.setMonth(month + 1)
  d.setDate(1)

  const resDate = String(d.getMonth() + 1).padStart(2, "0")
  const resMonth = String(d.getDate()).padStart(2, "0")
  const resYear = d.getFullYear()
  return `${resMonth}/${resDate}/${resYear}`
}

console.log(firstDayOfNextMonth("05/21/2020"))
console.log(firstDayOfNextMonth("12/21/2020"))
hgb123
  • 13,869
  • 3
  • 20
  • 38