How to set datetime on datetime-local via jQuery

前端 未结 7 2045
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-18 15:43

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?



        
7条回答
  •  不思量自难忘°
    2021-02-18 16:02

    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.

提交回复
热议问题