-1

/*
// * Setting a default value for the date box
document.getElementById("DATE").valueAsDate = new Date(); */
        <input type="datetime-local" id="DATE" value="2023-05-01T11:00" name="Date"
                                                placeholder="" class="vcheck" required minlength="8">

So if I uncomment the Javascript below I can set my value to today date but it over ride my value that I have set that hides the second. Is there any way to modify the javascript code I have so that I can still omit the seconds while having today date?

  • Does this answer your question? [How to set input type date's default value to today?](https://stackoverflow.com/questions/6982692/how-to-set-input-type-dates-default-value-to-today) – Fabio_MO May 08 '23 at 13:47
  • Unfortunately not I still need the time just not down to the exact second. Using Date instead of datetime local is not exact enough – genericdude76 May 08 '23 at 13:49
  • 1
    ``` let dateInput = document.getElementById("DATE"); dateInput.value = dateInput.value.split("T")[0] ``` – Shachar297 May 08 '23 at 14:22

1 Answers1

1

You could write a custom method to format the date to a string and set the value like so:

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById("DATE").value = formatDate(new Date());
});
Ivan
  • 114
  • 5