set date in input type date

后端 未结 12 1464
广开言路
广开言路 2020-11-28 23:51

i will set today date in datepicker input type date in chrome.

$(         


        
相关标签:
12条回答
  • 2020-11-28 23:52
        1 console.log(new Date())
        2. document.getElementById("date").valueAsDate = new Date();
    

    1st log showing correct in console =Wed Oct 07 2020 00:40:54 GMT+0530 (India Standard Time)

    2nd 06-10-2020 which is incorrect and today date is 07 and here showing 06.

    0 讨论(0)
  • 2020-11-28 23:55

    Fiddle link : http://jsfiddle.net/7LXPq/93/

    Two problems in this:

    1. Date control in HTML 5 accepts in the format of Year - month - day as we use in SQL
    2. If the month is 9, it needs to be set as 09 not 9 simply. So it applies for day field also.

    Please follow the fiddle link for demo:

    var now = new Date();
    
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    
    var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
    
    $('#datePicker').val(today);
    
    0 讨论(0)
  • 2020-11-28 23:55

    Update: I'm doing this with date.toISOString().substr(0, 10). Gives the same result as the accepted answer and has good support.

    0 讨论(0)
  • 2020-11-28 23:57

    Datetimepicker always needs input format YYYY-MM-DD, it doesn't care about display format of your model, or about you local system datetime. But the output format of datetime picker is the your wanted (your local system). There is simple example in my post.

    0 讨论(0)
  • 2020-11-29 00:00

    For me the shortest way to get locale date and in correct format for input type="date" is this :

    var d = new Date(); 
    var today = d.getFullYear()+"-"+("0"+(d.getMonth()+1)).slice(-2)+"-"+("0"+d.getDate()).slice(-2);
    

    Or this :

    var d = new Date().toLocaleDateString().split('/');
    var today = d[2]+"-"+("0"+d[0]).slice(-2)+"-"+("0"+d[1]).slice(-2);
    

    Then just set the date input value :

    $('#datePicker').val(today);
    
    0 讨论(0)
  • 2020-11-29 00:03

    to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.

    var today = moment().format('YYYY-MM-DD');
    $('#datePicker').val(today);
    
    0 讨论(0)
提交回复
热议问题