123

I just have a simple line of code like this:

<input type='date' min='1899-01-01' max='2000-01-01'>

Is there a simple way to set the max date to "today" instead of 2000-01-01? Or do I have to use Javascript to do this?

18 Answers 18

152

JavaScript only simple solution

datePickerId.max = new Date().toISOString().split("T")[0];
<input type="date" id="datePickerId" />

// below trick also works! Thanks jymbob for the comment.
datePickerId.max = new Date().toLocaleDateString('fr-ca')
9
  • 4
    It appears max it is not currently supported on iOS Safari. Check here for updates on this caniuse.com/#search=input%20date Mar 11, 2020 at 20:41
  • 2
    thanks to the helpful folks over in North America: today = new Date().toLocaleDateString('en-ca') - avoids odd off-by-one issues when ISOString() gets parsed to UTC
    – jymbob
    Sep 16, 2021 at 10:27
  • 2
    @jymbob Thanks! This is basically helpful for every user/browser that has a timezone offset (not just North America). It's not so much that 'en-ca' part does anything with the timezone (that's due to the toLocaleDateString method) but it so happens that the 'en-ca' locale displays a date in the exact way the input field needs it to be (YYY-MM-DD). So also for any other timezone in the world you should just use 'en-ca' as locale! Jan 27, 2022 at 16:01
  • 3
    Followup to my comment from 2021: From Chrome 110 en-ca no longer gives an ISO-friendly date, instead returning a standard North American m/d/y format. fr-ca is still yyyy-mm-dd
    – jymbob
    Feb 14, 2023 at 11:25
  • 1
    @jymbob thank you for keeping things up to date. I edited the answer. Feb 16, 2023 at 16:02
120

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

6
  • 7
    works perfectly.. wish HTML5 natively offered such feature or much flexible date format options
    – exexzian
    Aug 26, 2016 at 14:40
  • In addition to the front-end states, depending on the case you probably also need server side validation.
    – Dirk Jan
    Jan 15, 2020 at 10:27
  • Umm, I am attempting this, and it won't set the maximum date.. It still lets me select dates outside of the maximum, e.g. if today was the 25th of October, it's letting me select the 26th, 27th, 28th etc. Anyone know why?
    – Momoro
    Apr 8, 2020 at 5:31
  • thanks for the solution, how avoid that the user write a date that is not permitted, actually with this solution in the pick of the date is right the rule, but permit write a different date of the restriction Jul 7, 2020 at 6:34
  • The "input" element is meant to be self-closing. <input id="datefield" type='date' min='1899-01-01' max='2000-13-13' />. Dec 5, 2020 at 21:01
54

In lieu of Javascript, a shorter PHP-based solution could be:

 <input type="date" name="date1" max="<?= date('Y-m-d'); ?>">
17
  • 2
    You should use a proper templating system instead of mixing HTML and PHP code.
    – bfontaine
    Aug 8, 2017 at 14:55
  • 7
    @bfontaine clearly you haven't use php since in it both html and php is mixed
    – Pulkit
    Jul 8, 2018 at 23:25
  • 2
    @Pulkit The fact that you can doesn’t mean you should.
    – bfontaine
    Jul 9, 2018 at 8:33
  • 2
    @bfontaine mixing is a matter of choice some people like beer some people like cocktails, this example is great and save the manipulations with js or what ever example:
    – talsibony
    Oct 17, 2018 at 19:33
  • 4
    @bfontaine solution becomes bad when it creates another problem, I don't think this causing a problem in any way, in general mixing php and HTML in the same file it is not a problem at all.
    – talsibony
    Oct 18, 2018 at 16:09
19

Javascript will be required; for example:

$(function(){
    $('[type="date"]').prop('max', function(){
        return new Date().toJSON().split('T')[0];
    });
});

JSFiddle demo

2
  • 14
    And jquery aparrantly Sep 27, 2018 at 14:34
  • That's why my solution isn't that great. But the question is still why we can't do this natively without any JS involved
    – vmkcom
    Oct 5, 2018 at 4:59
10

Is you don't want to use external scripts, but rather set the max limit right in the HTML input element, inline as so:

<input type="date" max="3000-01-01" onfocus="this.max=new Date().toISOString().split('T')[0]" />

I've intentionally added the max attribute with a date far into the future, because it seems Chrome browser change the width of the field once a max attribute is set, so to avoid that, I had it pre-set.

See live demo

3
  • 5
    Best solution here in my opinion, thank you vsync, if anyone is trying to block out past dates like me, try this <input type="date" min="2050-01-01" onfocus="this.min=new Date().toISOString().split('T')[0]" />
    – EKrol
    Jul 8, 2021 at 18:39
  • What about if i wanna able to choose last 40 days? May 11, 2022 at 8:23
  • This topic is about a single date selection, not a range of dates. For selecting a range you would need 2 date inputs and a visual way to select a range which will eventually fill the values for those 2 fields
    – vsync
    May 11, 2022 at 9:10
8

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" />

1
  • thanks for the solution, how avoid that the user write a date that is not permitted, actually with this solution in the pick of the date is right the rule, but permit write a different date of the restriction Jul 7, 2020 at 6:34
6

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

<input ... max="{{ now()->toDateString('Y-m-d') }}">
3
  • in my case it didn't work, maybe, can also use this date('Y-m-d', strtotime($yourVariable))
    – Ismynr
    Apr 20, 2021 at 23:03
  • What if someone needs it only for js. Ans is out of scope for particular question Sep 6, 2021 at 10:26
  • Please read the question "Is there a simple way to set the max date to "today" instead of 2000-01-01? Or do I have to use Javascript to do this?" It is about another way than JS.
    – Strabek
    Sep 6, 2021 at 14:51
5

An alternative to .split("T")[0] without creating a string array in memory, using String.slice():

new Date().toISOString().slice(0, -14)

datePickerId.max = new Date().toISOString().slice(0, -14);
<input type="date" id="datePickerId" />

3

Yes, and no. There are min and max attributes in HTML 5, but

The max attribute will not work for dates and time in Internet Explorer 10+ or Firefox, since IE 10+ and Firefox does not support these input types.

EDIT: Firefox now does support it

So if you are confused by the documentation of that attributes, yet it doesn't work, that's why.
See the W3 page for the versions.

I find it easiest to use Javascript, s the other answers say, since you can just use a pre-made module. Also, many Javascript date picker libraries have a min/max setting and have that nice calendar look.

0
3

Examples with jQuery and JavaScript:

$('#arrival_date').attr('min', new Date().toISOString().split('T')[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="date" name="arrival_date" id="arrival_date" class="form-control" aria-label="...">

document.getElementById('arrival_date').setAttribute('min', new Date().toISOString().split('T')[0])
<input type="date" name="arrival_date" id="arrival_date" class="form-control" aria-label="...">

2

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')]
                   ));
2
  • 1
    Introducing Symfony for such a basic requirement looks a bit weird
    – Nico Haase
    Apr 5, 2018 at 10:18
  • Ok, in fact I was here from google and there were "symfony" in my search so I thought it can help Apr 5, 2018 at 10:58
2

Example with React

import Input from "./components/Input";

const DateInput = () => {
  const today = new Date().toISOString().split("T")[0];
  return <Input type="date" max={today} />
}

export default DateInput;
1

A short but may be less readable version of one of the previous answers.

   <script type="text/javascript">
    $(document).ready(DOM_Load);

    function DOM_Load (e) {
        $("#datefield").on("click", dateOfBirth_Click);
    }

    function dateOfBirth_Click(e) {
        let today = new Date();
        $("#datefield").prop("max", `${today.getUTCFullYear()}-${(today.getUTCMonth() + 1).toString().padStart(2, "0")}-${today.getUTCDate().toString().padStart(2, "0")}`);
    }

</script>
1

Yes... you have to use Javascript. My solution below is just yet another option which you can pick up.

var today = new Date().toJSON().slice(0, 10);
var date = $('#date-picker');
date.attr('max', today);
1
  • 2
    jQuery date-picker is a vastly different component from standard date input.
    – nsimeonov
    Jun 2, 2022 at 23:03
0

Template: ejs

Using Node.js, express.js and template System ejs:

<input id="picOfDayDate" type="date"  name="date-today"
    value="<%= new Date().toISOString().split("T")[0] %>" 
    min='1995-06-16' 
    max="<%= new Date().toISOString().split("T")[0] %>" 
    class="datepicker" 
>
0

First, you need to get today's date by

const [today] = new Date().toISOString().split('T')

Then get the max date

  const maxDate = new Date();
  maxDate.setDate(maxDate.getDate() + 30);
  const [maxDateFormatted] = maxDate.toISOString().split('T');

Then set the min and max attributes.

  const dateInput = document.getElementById('myDateInput');
  dateInput.setAttribute('min', today);
  dateInput.setAttribute('max', maxDateFormatted);

This is working example

const [today] = new Date().toISOString().split('T');

const maxDate = new Date();
maxDate.setDate(maxDate.getDate() + 30);
const [maxDateFormatted] = maxDate.toISOString().split('T');

const dateInput = document.getElementById('myDateInput');
dateInput.setAttribute('min', today);
dateInput.setAttribute('max', maxDateFormatted);
<input type="date" id="myDateInput"></input>

0

PHP Base

<input type="date" name="date1" max="<?= date('Y-m-d'); ?>">

C# Base

<input type="date" name="date1" max="@DateTime.Now.ToString("yyyy-MM-dd")">
-1

I also had same issue .I build it trough this way.I used struts 2 framework.

  <script type="text/javascript">

  $(document).ready(function () {
  var year = (new Date).getFullYear();
  $( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate: 
  0});

  });


  </script>

        <s:textfield name="effectiveDate" cssClass="input-large" 
   key="label.warrantRateMappingToPropertyTypeForm.effectiveDate" 
   id="effectiveDateId" required="true"/>

This worked for me.

Not the answer you're looking for? Browse other questions tagged or ask your own question.