28

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

32

You can make it shorter:

<input type="datetime-local" id="cal"> 
function toLocalISOString(date) { const localDate = new Date(date - date.getTimezoneOffset() * 60000); //offset in milliseconds. Credit https://stackoverflow.com/questions/10830357/javascript-toisostring-ignores-timezone-offset // Optionally remove second/millisecond if needed localDate.setSeconds(null); localDate.setMilliseconds(null); return localDate.toISOString().slice(0, -1); } window.addEventListener("load", () => { document.getElementById("cal").value = toLocalISOString(new Date()); }); 
Sign up to request clarification or add additional context in comments.

3 Comments

In Firefox i had to slice away the seconds (-8) to get the form to validate.
Best response here, if you want to to remove milliseconds just add now.setMilliseconds(null)
Great answer! And likewise, to remove seconds, use now.setSeconds(null).
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 Comments

The default value sets alright, but why doesn't it change when selecting another date/time from the picker?
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.
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 Comment

Warning: input type="datetime" is obsolete, and is already unsupported by most browsers. Use type="datetime-local" instead. See: developer.mozilla.org/en-US/docs/Web/HTML/Element/input/…
7

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; }); 

Comments

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;

Comments

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())}`; } 

Comments

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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.