0

I have implemented this solution to my school project

However I get this error from the console whenever I attempt to change the value of the initial date field

The specified value "2/21/2023" does not conform to the required format, "yyyy-MM-dd".

What could be wrong in the solution as it works in the example given

I tried change the

dueDateInput.value = dueDate.toLocaleDateString('en-CA');

into

dueDateInput.value = dueDate.toISOString();

and also

dueDateInput.value = dueDate.toLocaleDateString('bo-CN');

but to no avail

Since the browser says that this is the codeline that gives the error, how can I convert the dueDate to YYYY-MM-DD so that I can assign it as the value to the other date field

Phil
  • 157,677
  • 23
  • 242
  • 245
ringring18
  • 19
  • 4

2 Answers2

0

The issue with .toISOString() is that it returns a full date and timestamp, while all you want is the date part. You can use date.getFullYear(), date.getMonth(), and date.getDate()} to get the full date. Here's an example:

const dateInput = document.getElementById('date');

const date = new Date(); // by default, today's date
dateInput.value = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate()}`;
<input type="date" id="date">
Michael M.
  • 10,486
  • 9
  • 18
  • 34
0

You can avoid using date strings and simply set the valueAsDate property instead.

This allows you to work directly with Date instances which makes date arithmetic much easier.

const dateCreatedInput = document.getElementById("date-created");
const addMonthsInput = document.getElementById("add-months");
const dueDateInput = document.getElementById("due-date");

const setDueDate = () => {
  const dateCreated = dateCreatedInput.valueAsDate;
  if (dateCreated) {
    dateCreated.setMonth(dateCreated.getMonth() + addMonthsInput.valueAsNumber);
    dueDateInput.valueAsDate = dateCreated;
  }
};

dateCreatedInput.addEventListener("change", setDueDate);
addMonthsInput.addEventListener("change", setDueDate);
<p>
<label for="date-created">Date created:</label>
<input type="date" id="date-created"/>
</p>
<p>
<label for="add-months">Add months:</label>
<input type="number" id="add-months" min="1" value="1"/>
</p>
<p>
<label for="due-date">Due date:</label>
<input type="date" id="due-date" readonly/>
</p>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 2
    On 31 January, this "add one month" algorithm returns 3 March. That might be unexpected. See [*JavaScript function to add X months to a date*](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date). – RobG Feb 21 '23 at 10:19