29

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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179

9 Answers9

30

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.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
16

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.

Varun Natraaj
  • 7,402
  • 2
  • 18
  • 19
  • It's not working because all javascript date's methods returns a value without the a leading zero. http://stackoverflow.com/a/3605248/792624 – jacoz May 06 '14 at 07:29
  • Edited. Try and let me know :) – Varun Natraaj May 11 '14 at 08:23
  • 6
    **Note** `new Date().toJSON().slice(0,19)` and `new Date().toISOString().slice(0,19)` both returns UTC-time, not __local time__. – Hasse Björk Dec 05 '15 at 22:31
  • 2
    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()));` – James Sep 08 '16 at 10:05
  • I've edited to include the zero padding that @James points out – lucasvw Aug 30 '18 at 21:07
  • @lucasvw I'm not seeing that edit FYI... I'll put a request a in to edit it. – MackProgramsAlot Jun 30 '21 at 19:20
  • All this time and it's still wrong. Minutes and seconds must also be zero padded. – Jonathan Wood Sep 02 '21 at 17:10
11

What about?

var now=new Date();
console.log(new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().substring(0,19));
klaudyuxxx
  • 374
  • 2
  • 13
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);
rb-
  • 2,315
  • 29
  • 41
5

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')
Twinstar
  • 61
  • 1
  • 4
2

Here is a simpler way to do it.

const now = (new Date().toLocaleString("sv-SE") + '').replace(' ','T');
console.log(now);
Pumpkin Pie
  • 510
  • 1
  • 4
  • 15
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).

jgmjgm
  • 4,240
  • 1
  • 25
  • 18
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"

sifr_dot_in
  • 3,153
  • 2
  • 33
  • 42
0

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

dotcoder
  • 2,828
  • 10
  • 34
  • 50