skip to Main Content

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

2

Answers


  1. 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">
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search