594

Given an input element:

<input type="date" /> 

Is there any way to set the default value of the date field to today's date?

0

46 Answers 46

402

Like any HTML input field, the browser will leave the date element empty unless a default value is specified within the value attribute. Unfortunately, HTML5 doesn't provide a way of specifying 'today' in the HTMLInputElement.prototype.value.

One must instead explicitly provide a RFC3339 formatted date (YYYY-MM-DD). For example:

element.value = "2011-09-29" 
Sign up to request clarification or add additional context in comments.

15 Comments

for .net users: DateTime.Today.ToString("yyyy-MM-dd")
Note that the '0' in front of month and day are necessary: "2011-09-29" works, "2011-9-29" does not.
Ruby: (Also) DateTime.now.strftime("%Y-%m-%d")
@MartinBarker wouldn't that be date('Y-m-d') as it requires the leading zero?
For JavaScript: myDate.toLocaleDateString('en-CA') does the trick
|
328

Use HTMLInputElement.prototype.valueAsDate:

document.getElementById('datePicker').valueAsDate = new Date(); 

6 Comments

is it working in all browsers ? and mobile versions as well ? Tested ?
@UsmanY It's part of the HTML5 spec, so anything that supports HTML5 input types should support valueAsDate. html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
@harbichidian The proposal for date input predates the proposal for valueAsDate by a while. Do you have a link to browser support for that property?
The date will be converted into UTC time. If you're at 6pm on 2018-03-27 in -0600 and you set the valueAsDate to new Date(), the fields value will be set to 2018-03-28. See austinfrance.wordpress.com/2012/07/09/…
As @Aupajo said, this sets the wrong date if you don't want UTC time.
|
282

The JavaScript Date object provides enough built-in support for the required format to avoid doing it manually:

Add this for correct timezone support*:

Date.prototype.toDateInputValue = (function() { var local = new Date(this); local.setMinutes(this.getMinutes() - this.getTimezoneOffset()); return local.toJSON().slice(0,10); }); 

jQuery:

$(document).ready( function() { $('#datePicker').val(new Date().toDateInputValue()); });​ 

Pure JS:

document.getElementById('datePicker').value = new Date().toDateInputValue(); 

⚠️ * Important update: The original answer contains code that modifies the native Date prototype which is something that should be avoided. Here's the functional approach which is 100% safe and should be used instead:

function toDateInputValue(dateObject){ const local = new Date(dateObject); local.setMinutes(dateObject.getMinutes() - dateObject.getTimezoneOffset()); return local.toJSON().slice(0,10); }; document.getElementById('datePicker').value = toDateInputValue(new Date()); 

jQuery:

$(document).ready( function() { $('#datePicker').val(toDateInputValue(new Date())); });​ 

31 Comments

Watch out if you're supporting mobile. On Android 4.0.3 (at least) I've had issues where the new date selected via the popup date control is appended to todays date, rather than replaces it. E.g. you can end up with 2013-03-252013-03-27 rather than 2013-03-25, and there's no way for the user to change it.
@Web_Designer Fair enough. You'll want to adjust with local.setMinutes(this.getMinutes() - this.getTimezoneOffset()); (as that answer eventually gets to) first, then.
This only sets the value property, it doesn't set the attribute so if the form is reset, it defaults to no value. Also, it would be a lot clearer to use toISOString, which is what toJSON calls anyway.
@apraetor Actually, it's the other way around, since only browsers that support date inputs support valueAsDate (that leaves out IE, Firefox, maybe Safari, basically everything but Chrome, Opera, Edge, and some mobile browsers). Everything supports the value property my solution uses, even when date inputs fall back to text inputs in the non-supporting browsers, the other solution will error or fail.
This answer worked for me using a input[type=datetime-local] and changing it to slice(0,19) HTH
|
150

This relies upon PHP:

<input type="date" value="<?php echo date('Y-m-d'); ?>" /> 

9 Comments

Your answer depends on php completely.
If you're contact form is on a PHP page (for example, on a WordPress page or shortcode), this works perfectly. Many thanks Isham!
You could reduce redundancy by changing <?php echo date('Y-m-d', strtotime(date('Y/m/d'))); ?> to <?php echo date('Y-m-d'); ?>
This sets the date according to the creation date (in a server, in the server’s time zone) of the HTML document. It need not match the current date, as of actually filling out the field. Client-side JavaScript is better if you need to do things that depend on the user’s side.
you can also use short tag <?= date('Y-m-d'); ?>. One "echo" less
|
49

You could fill the default value through JavaScript as seen here:

http://jsfiddle.net/7LXPq/

$(document).ready( function() { var now = new Date(); var month = (now.getMonth() + 1); var day = now.getDate(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; var today = now.getFullYear() + '-' + month + '-' + day; $('#datePicker').val(today); }); 

I would probably put a bit of extra time to see if the month and date are single digits and prefix them with the extra zero...but this should give you an idea.

EDIT: Added check for the extra zero.

1 Comment

In Opera (tested on Opera 12 / Windows) this doesn't work if you don't put the leading zeros in month and day.
41

In HTML5 as such, there is no way to set the default value of the date field to today’s date? As shown in other answers, the value can be set using JavaScript, and this is usually the best approach if you wish to set the default according to what is current date to the user when the page is loaded.

HTML5 defines the valueAsDate property for input type=date elements, and using it, you could set the initial value directly from an object created e.g. by new Date(). However, e.g. IE 10 does not know that property. (It also lacks genuine support to input type=date, but that’s a different issue.)

So in practice you need to set the value property, and it must be in ISO 8601 conformant notation. Nowadays this can be done rather easily, since we can expect currenty used browsers to support the toISOString method:

<input type=date id=e> <script> document.getElementById('e').value = new Date().toISOString().substring(0, 10); </script> 

2 Comments

Or if you want it to be Y10K compliant: = new Date().toISOString().split('T')[0];
toISOString returns a UTC date and time, so may not show the correct date for the user's timezone. E.g. if the user is UTC+0800, then from midnight until 08:00 they will get yesterday's date.
37

Follow the standard Y-m-d format, if you are using PHP

<input type="date" value="<?php echo date("Y-m-d"); ?>"> 

1 Comment

you should mention that this answer works if you're using php, this is not the case for everyone .
36

HTML

<input type="date" id="theDate"> 

JQuery

$(document).ready(function() { var date = new Date(); var day = date.getDate(); var month = date.getMonth() + 1; var year = date.getFullYear(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; var today = year + "-" + month + "-" + day +"T00:00"; $("#theDate").attr("value", today); }); 

demo

If you don't want to use jQuery you can do something like this

JS

var date = new Date(); var day = date.getDate(); var month = date.getMonth() + 1; var year = date.getFullYear(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; var today = year + "-" + month + "-" + day; document.getElementById("theDate").value = today; 

demo

TS

const date = new Date() const year = date.getFullYear() let month: number | string = date.getMonth() + 1 let day: number | string = date.getDate() if (month < 10) month = '0' + month if (day < 10) day = '0' + day const today = `${year}-${month}-${day}` document.getElementById("theDate").value = today; 

Comments

29

HTML:

<input type="date" value="2022-01-31"> 

PHP:

<input type="date" value="<?= date('Y-m-d') ?>"> 

Date format must be "yyyy-mm-dd"

1 Comment

Your HTML solution is super neat!
24

If you're doing anything related to date and time in the brower, you want to use Moment.js:

moment().format('YYYY-MM-DD'); 

moment() returns an object representing the current date and time. You then call its .format() method to get a string representation according to the specified format. In this case, YYYY-MM-DD.

Full example:

<input id="today" type="date"> <script> document.getElementById('today').value = moment().format('YYYY-MM-DD'); </script> 

2 Comments

If you already have moment() available or plan to do more date work in your web app, this solution is a no-brainer. Moment solves so many issues.
For anyone looking in 2024 or later: Please note that the Moment.js authors recommends against using Moment.js. They don't directly recommend a single replacement, but these are their suggestions: Luxon, Day.js, date-fns or js-Joda.
23

Javascript

document.getElementById('date-field').value = new Date().toISOString().slice(0, 10); 

Jquery

$('#date-field').val(new Date().toISOString().slice(0, 10)); 

Another Option

If you want to customize the date, month and year just do sum or sub as your wish 😎 For month is started form 0 that is why need to sum 1 with the month.

function today() { let d = new Date(); let currDate = d.getDate(); let currMonth = d.getMonth()+1; let currYear = d.getFullYear(); return currYear + "-" + ((currMonth<10) ? '0'+currMonth : currMonth )+ "-" + ((currDate<10) ? '0'+currDate : currDate ); } 

Appy the today function

document.getElementById('date-field').value = today(); $('#date-field').val(today()); 

Comments

13

Simplest working version I tested:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="date" id="date" name="date"> <script> $('#date').val(new Date().toJSON().slice(0,10)); </script>

Comments

12

use moment.js to solve this issue in 2 lines, html5 date input type only accept "YYYY-MM-DD" this format. I solve my problem this way.

var today = moment().format('YYYY-MM-DD'); $('#datePicker').val(today); 

this is simplest way to solve this issue.

Comments

10

This is very much simple by applying following code, Using PHP

<input type="date" value="<?= date('Y-m-d', time()); ?>" /> 

Date function will return current date, by taking date in time().

1 Comment

Can just do - date('Y-m-d'); for shorter.
8
<input id="datePicker" type="date" /> 

$(document).ready( function() { 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); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="datePicker" type="date" />

Comments

8

Both top answers are incorrect.

A short one-liner that uses pure JavaScript, accounts for the local timezone and requires no extra functions to be defined:

const element = document.getElementById('date-input'); element.valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000;
<input id='date-input' type='date'>

This gets the current datetime in milliseconds (since epoch) and applies the timezone offset in milliseconds (minutes * 60k milliseconds per minute).

You can set the date using element.valueAsDate but then you have an extra call to the Date() constructor.

Comments

6

Very Simple, Just use server side languages like PHP,ASP,JAVA or even you can use javascript.

Here is the solution

<?php $timezone = "Asia/Colombo"; date_default_timezone_set($timezone); $today = date("Y-m-d"); ?> <html> <body> <input type="date" value="<?php echo $today; ?>"> </body> </html> 

Comments

6

It is possible in one line of JS.

HTML:

<input type="date" id="theDate"> 

JS:

document.getElementById('theDate').value = new Date().toISOString().substring(0, 10); 

document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
<input type="date" id="theDate">

Comments

5

if you need to fill input datetime you can use this:

<input type="datetime-local" name="datetime" value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" /> 

Comments

5

For NodeJS (Express with SWIG templates):

<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" /> 

Comments

5

The simplest solutions seem to overlook that UTC time will be used, including highly up-voted ones. Below is a streamlined, ES6, non-jQuery version of a couple of existing answers:

const today = (function() { const now = new Date(); const month = (now.getMonth() + 1).toString().padStart(2, '0'); const day = now.getDate().toString().padStart(2, '0'); return `${now.getFullYear()}-${month}-${day}`; })(); console.log(today); // as of posting this answer: 2019-01-24 

1 Comment

You should state which property of an input element to assign it to. value or valueAsDate? Looks good though.
4

This is what I did in my code, I have just tested and it worked fine, input type="date" does not support to set curdate automatically, so the way I used to overcome this limitation was using PHP code a simple code like this.

<html> <head></head> <body> <form ...> <?php echo "<label for='submission_date'>Data de submissão</label>"; echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>"; ?> </form> </body> </html> 

Hope it helps!

1 Comment

Hi and welcome to SO, Please Add more information to support your code and make sure that the person asking the question is wanting a PHP based solution.
4

This is something you really need to do server-side as each user's local time format differs, not to mention each browser behaves different.

Html Date inputs value should be in this format: yyyy-mm-dd otherwise it will not show a value.

ASP CLASSIC , OR VBSCRIPT:

current_year = DatePart("yyyy",date) current_month = DatePart("m",date) current_day = DatePart("d",date) IF current_month < 10 THEN current_month = "0"&current_month END IF IF current_day < 10 THEN current_day = "0"&current_day END IF get_date = current_year&"-"&current_month&"-"&current_day Response.Write get_date 

Output of today's date : 2019-02-08

Then in your html: <input type="date" value="<% =get_date %>"

PHP

just use this: <input type="date" value="<?= date("Y-m-d"); ?>">

Comments

4

To match the original query.

date.value = new Date().toJSON().split('T')[0]
<input type="date" id="date"/>

Comments

3

Even after all these time, it might help someone. This is simple JS solution.

JS

 let date = new Date(); let today = date.toISOString().substr(0, 10); //console.log("Today: ", today);//test document.getElementById("form-container").innerHTML = '<input type="date" name="myDate" value="' + today + '" >';//inject field 

HTML

 <form id="form-container"></form> 

Similar solution works in Angular without any additional library to convert date format. For Angular (code is shortened due to common component code):

//so in myComponent.ts //Import.... @Component...etc... date: Date = new Date(); today: String; //<- note String //more const ... export class MyComponent implements OnInit { //constructor, etc.... ngOnInit() { this.today = this.date.toISOString().substr(0, 10); } } //so in component.html <input type="date" [(ngModel)]="today" /> 

2 Comments

This is way too cumbersome for just needing to use a default value.
Which one of two independent examples you are trying to point out? Its 4 lines of codes in both examples.... First example is pure html +js so create container and copy paste code its 3 lines if you don't count comments. Same for angular example which was the reason i left comment. Not sure what you meant....
3

A future proof solution, also an alternative to .split("T")[0] that doesn't create a string array in memory, would be using String.slice() as shown below:

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

A lot of the answers given here, such as slice(0, 10), substring(0, 10) etc will fail in the future.
They use Date.toJSON() which returns Date.toISOString():

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

Once the year becomes 5 digit, these answers will fail.

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

Comments

3

This returns in the same YYYY-MM-DD format as in ISO but in your local time instead of being UTC.

function getToday() { return new Date().toLocaleDateString('en-CA', { year: 'numeric', month: '2-digit', day: '2-digit' }); } 

Comments

3

Use .defaultValue property of the input:date element to set the default value of the date to today's date.

<input type="date" id="date"/> window.onload = function loadDate() { let date = new Date(), day = date.getDate(), month = date.getMonth() + 1, year = date.getFullYear(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; const todayDate = `${year}-${month}-${day}`; document.getElementById("date").defaultValue = todayDate; }; loadDate(); 

Or make it IIFE/self-called function, on window load

window.onload = (function loadDate() { let date = new Date(), day = date.getDate(), month = date.getMonth() + 1, year = date.getFullYear(); if (month < 10) month = "0" + month; if (day < 10) day = "0" + day; const todayDate = `${year}-${month}-${day}`; document.getElementById("date").defaultValue = todayDate; })(); 

Using defaultValue property gives dynamic advantage, unlike setting the date using the value attribute.

Also, note that the date format must be matched, hence my use of the format for todayDate as:

yyyy-mm-dd

I believe this answers your question, except you want to set a static start and end date. To do this, kindly follow the example below from Mozilla:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date>

Comments

2

by Javascript:

var today = new Date(); document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2); 

Comments

2
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1) 

1 Comment

Please add description with your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.