23

Is there anyway that I can make a default value of HTML5 input type='datetime-local' to today's date and this current time.

Thanks before

7 Answers 7

26

You can make it shorter:

<input type="datetime-local" id="cal">
window.addEventListener('load', () => {
  var now = new Date();
  now.setMinutes(now.getMinutes() - now.getTimezoneOffset());

  /* remove second/millisecond if needed - credit ref. https://stackoverflow.com/questions/24468518/html5-input-datetime-local-default-value-of-today-and-current-time#comment112871765_60884408 */
  now.setMilliseconds(null)
  now.setSeconds(null)

  document.getElementById('cal').value = now.toISOString().slice(0, -1);
});
3
  • In Firefox i had to slice away the seconds (-8) to get the form to validate.
    – jared
    Aug 31, 2020 at 11:46
  • 5
    Best response here, if you want to to remove milliseconds just add now.setMilliseconds(null)
    – Heichou
    Sep 10, 2020 at 12:41
  • Great answer! And likewise, to remove seconds, use now.setSeconds(null).
    – Matt
    May 12, 2022 at 20:52
9

The accepted answer seems pretty complicated to me... here a shorter solution that doesn't need jQuery

JSFiddle: https://jsfiddle.net/rzaceg8v/

window.addEventListener("load", function() {
    var now = new Date();
    var utcString = now.toISOString().substring(0,19);
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var localDatetime = year + "-" +
                      (month < 10 ? "0" + month.toString() : month) + "-" +
                      (day < 10 ? "0" + day.toString() : day) + "T" +
                      (hour < 10 ? "0" + hour.toString() : hour) + ":" +
                      (minute < 10 ? "0" + minute.toString() : minute) +
                      utcString.substring(16,19);
    var datetimeField = document.getElementById("myDatetimeField");
    datetimeField.value = localDatetime;
});
<input type="datetime-local" id="myDatetimeField"/>

2
  • The default value sets alright, but why doesn't it change when selecting another date/time from the picker?
    – nimsrules
    Aug 8, 2020 at 11:20
  • That's a good question. It used to work and it still works in Chromium based Edge. I think it may be a bug in the new Chrome version.
    – ndreisg
    Aug 10, 2020 at 9:30
7

It's possible. By using a JQuery function, you can have a really complete solution.

Here is an example.

JSFiddle http://jsfiddle.net/v8MNx/1/

HTML

<form action="demo.html" id="myForm">
    <p>
        <label>Date:</label>
        <input type="datetime" name="anniversaire" id="anniversaire"/>
    </p>
    <input type="submit" value="Submit"/>
</form>

JQuery:

//Function found here: https://gist.github.com/ryanburnette/8803238
$.fn.setNow = function (onlyBlank) {
  var now = new Date($.now())
    , year
    , month
    , date
    , hours
    , minutes
    , seconds
    , formattedDateTime
    ;

  year = now.getFullYear();
  month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
  date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
  hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
  minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
  seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();

  formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;

  if ( onlyBlank === true && $(this).val() ) {
    return this;
  }

  $(this).val(formattedDateTime);

  return this;
}

$(function () {
    // Handler for .ready() called.
    $('input[type="datetime"]').setNow();

});
1
5

The methods above worked but were too verbose for me. Here's my version:

window.addEventListener("load", function() {
    var now = new Date();
    var offset = now.getTimezoneOffset() * 60000;
    var adjustedDate = new Date(now.getTime() - offset);
    var formattedDate = adjustedDate.toISOString().substring(0,16); // For minute precision
    var datetimeField = document.getElementById("myDatetimeField");
    datetimeField.value = formattedDate;
});

1

This worked perfectly!

One note, I tried this the only month it would break, October. It would give me a '010', instead of 10.

month = (now.getMonth() +1 ).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;

1

Big line works for me, if it doesn't for you you can introduce whitespaces and line breaks in the expressions.

    function setDatetimeInput(element, t = new Date()){
        function p(number){return number.toString().padStart(2, '0');}//number to 2 digit, 0 padded string
        element.value = `${t.getFullYear()}-${p(t.getMonth()+1)}-${p(t.getDate())}T${p(t.getHours())}:${p(t.getMinutes())}`;
    }
0

here's a simple way:

<input type="datetime-local" id="cal">
const currentDateTime = () => {
  var tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
  var localISOString = new Date(Date.now() - tzoffset)
    .toISOString()
    .slice(0, -1);

  // convert to YYYY-MM-DDTHH:MM
  const datetimeInputString = localISOString.substring(
    0,
    ((localISOString.indexOf("T") | 0) + 6) | 0
  );
  console.log(datetimeInputString);
  return datetimeInputString;
};

document.getElementById('cal').value = currentDateTime();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.