30

I have datetime-local html control on my form and I need to set date and time on it dynamically via JS or jQuery. How can I do it?

<input type="datetime-local" id="publishDate" required/>

I tried

$("#publishDate").val("2013-3-18 13:00");
$("#publishDate").val("2013-3-18T13:00");
$("#publishDate").val(new Date().toLocalString());

but nothing worked.

9 Answers 9

31

This would do the trick

$("#publishDate").val("2013-03-18T13:00");

You need to use 2 digits for the month to make your sample work.

Sign up to request clarification or add additional context in comments.

Comments

15

If you want to set the current date, then you can try this:

__Method 1:__

$(document).ready(function(){
    $('input[type=datetime-local]').val(new Date().toJSON().slice(0,19));
});

__Method 2:__

function zeroPadded(val) {
  if (val >= 10)
    return val;
  else
    return '0' + val;
}

$(document).ready(function(){
  d = new Date();
  $('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
});

Note: You can replace $('input[type=datetime-local]') with Id or Name or Class of the datetime-local field.

EDIT: d.getMonth() returns a value between 0-11, so to input the proper month 1 needs to be added to the result.

7 Comments

It's not working because all javascript date's methods returns a value without the a leading zero. stackoverflow.com/a/3605248/792624
Edited. Try and let me know :)
Note new Date().toJSON().slice(0,19) and new Date().toISOString().slice(0,19) both returns UTC-time, not local time.
I've modified the script slightly, you need to use the zeroPadded function on the hours minutes and seconds else you'll get an error. $('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+zeroPadded(d.getHours())+":"+zeroPadded(d.getMinutes())+":"+zeroPadded(d.getSeconds()));
I've edited to include the zero padding that @James points out
|
11

What about?

var now=new Date();
console.log(new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().substring(0,19));

Comments

7

Here's a solution in formatting the date using momentjs.
This will get the current date and time

moment().format('YYYY-MM-DDThh:mm:ss.SSS')

Comments

5

I wrote a jQuery method that sets the current UTC time. It's useful for initializing datetime and datetime-local input fields.

Here's how you would use it to initialize a field.

$('input[type="datetime"]').setNow();

Or pass an argument of true to only set fields with no value.

$('input[type="datetime"]').setNow(true);

2 Comments

thanks your jQuery extention did the trick! gist.github.com/ryanburnette/8803238
Great to hear! That reminds me that I need to clean up that snippet.
3

Here is a simpler way to do it.

const now = (new Date().toLocaleString("sv-SE") + '').replace(' ','T');
console.log(now);

Comments

1

Using moment, you can do the following.

  1. If you want to use the current date.

    $("#publishDate").val(moment().format('YYYY-MM-DDTHH:MM'));

  2. If you have a specified date.

    $("#publishDate").val(moment(yourDate).format('YYYY-MM-DDTHH:MM'));

Comments

0

This component is messed up because it's not specified properly yet. Implementations are likely to be quirky as well.

The right way to do it should be to pass a date object, with JS and DOM it would make no sense to not have this. Doing things with string manipulation is going to invoke Zalgo. Sooner or later it will break with the locale or timezone.

I have looked for something like this and in Chrome 46 found:

$('input[type=datetime-local]').prop('valueAsNumber', Math.floor(new Date() / 60000) * 60000); // 60seconds * 1000milliseconds

If you don't remove the second and milliseconds they will show in the input field.

There is a valueAsDate property as well but mysteriously:

Uncaught DOMException: Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date values.

So they haven't finished implementing it yet or choose a bad name for that property (it shows as null even when something is set though).

Comments

0

for those who have date in string format with "T" character in between,
replace the 10 character (space) with T
with below code:

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substring(0,index) + chr + str.substring(index+1);
}
var variable=setCharAt("2022-02-26 16:32",10,"T");
$("#publishDate").val(variable);

but remember that the format must be in "YYYY-MM-DDThh:mm:ss"
the OP has made the mistake of providing date "2013-3-18T13:00"
where as the month should have been "03"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.