Set date input field's max date to today

前端 未结 10 594
说谎
说谎 2020-12-02 19:37

I just have a simple line of code like this:


Is there a sim

相关标签:
10条回答
  • 2020-12-02 20:27

    it can be useful : If you want to do it with Symfony forms :

     $today = new DateTime('now');
     $formBuilder->add('startDate', DateType::class, array(
                       'widget' => 'single_text',
                       'data'   => new \DateTime(),
                       'attr'   => ['min' => $today->format('Y-m-d')]
                       ));
    
    0 讨论(0)
  • 2020-12-02 20:29

    I am using Laravel 7.x with blade templating and I use:

    <input ... max="{{ now()->toDateString('Y-m-d') }}">
    
    0 讨论(0)
  • 2020-12-02 20:34

    You will need Javascript to do this:

    HTML

    <input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>
    

    JS

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
     if(dd<10){
            dd='0'+dd
        } 
        if(mm<10){
            mm='0'+mm
        } 
    
    today = yyyy+'-'+mm+'-'+dd;
    document.getElementById("datefield").setAttribute("max", today);
    

    JSFiddle demo

    0 讨论(0)
  • 2020-12-02 20:38

    toISOString() will give current UTC Date. So to get the current local time we have to get getTimezoneOffset() and subtract it from current time

    document.getElementById('dt').max = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split("T")[0];
    <input type="date" min='1899-01-01' id="dt" />

    0 讨论(0)
提交回复
热议问题