[html] How to set input type date's default value to today?

The HTML5 input types are great, Opera's new built-in date picker is a breeze, and Chrome has at least supported the new input type with a spin-wheel implementation.

But is there any way to set the default value of the date field to today's date? With Opera, I can choose 'Today' from the date picker, and as soon as I click on either of the step buttons in Chrome, it increments/decrements from today's date.

I'm not shy to code a solution to this minor problem, but it seems silly to me that both of the browsers are fully aware of the current date but won't automatically just pop it in (at least as a placeholder).

This question is related to html date input

The answer is


this works for me:

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

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement


Here is an easy way to do this with javascript.

    var date = new Date();
    var datestring = ('0000' + date.getFullYear()).slice(-4) + '-' + ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2) + 'T'+  ('00' +  date.getHours()).slice(-2) + ':'+ ('00' + date.getMinutes()).slice(-2) +'Z';
    document.getElementById('MyDateTimeInputElement').value = datestring;

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

$(document).ready(function(){
  var date = new Date();

  var day = ("0" + date.getDate()).slice(-2); var month = ("0" + (date.getMonth() + 1)).slice(-2);

  var today = date.getFullYear()+"-"+(month)+"-"+(day) ;
});

$('#dateid').val(today);

For NodeJS (Express with SWIG templates):

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

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'); ?>" />

Like any HTML input field, the browser will leave it empty unless a default value is specified with the value attribute.

Unfortunately HTML5 doesn't provide a way of specifying 'today' in the value attribute (that I can see), only a RFC3339 valid date like 2011-09-29.

TL;DR Use YYYY-MM-DD date format or it won't display


If you are using ruby you can use this to set the default value to today's date and time:

<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />

Since Date type only accepts the format "yyyy-MM-dd", you need to format the date value accordingly.

Here is the solution for this,

var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;

if (month_actual < 10) {
  month_actual = "0"+month_actual; 
  }

var day_val = d.getDate();
if (day_val < 10) {
  day_val = "0"+day_val; 
  }

document.getElementById("datepicker_id").value = d.getFullYear()+"-"+ month_actual +"-"+day_val;

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>

Thanks peter, now i change my code.

<input type='date' id='d1' name='d1'>

<script type="text/javascript">
var d1 = new Date();
var y1= d1.getFullYear();
var m1 = d1.getMonth()+1;
if(m1<10)
    m1="0"+m1;
var dt1 = d1.getDate();
if(dt1<10)
dt1 = "0"+dt1;
var d2 = y1+"-"+m1+"-"+dt1;
document.getElementById('d1').value=d2;
</script>

by Javascript:

var today = new Date();

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

I had the same problem and I fixed it with simple JS. The input:

<input type="date" name="dateOrder" id="dateOrder"  required="required">

the JS

<script language="javascript">
document.getElementById('dateOrder').value = "<?php echo date("Y-m-d"); ?>";
</script>

Important: the JS script should be in the last code line, or after to input, because if you put this code before, the script won't find your input.


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


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>

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();

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

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

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:

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

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

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


And for those using ASP VBScript

<%
'Generates date in yyyy-mm-dd format
Function GetFormattedDate(setDate)
strDate = CDate(setDate)
strDay = DatePart("d", strDate)
strMonth = DatePart("m", strDate)
strYear = DatePart("yyyy", strDate)
If strDay < 10 Then
  strDay = "0" & strDay
End If
If strMonth < 10 Then
  strMonth = "0" & strMonth
End If
GetFormattedDate = strYear & "-" & strMonth & "-" & strDay
End Function
%>

And then in the body, your element should look something like this

<input name="today" type="date" value="<%= GetFormattedDate(now) %>" />

Cheers!


Since there's no default method of setting the value to today's date, I would say this should be dependent upon it's application. If you're looking to maximize your audience's exposure to the date picker, then use a server-side script (PHP, ASP, etc.) to set the default value.

However, if it's for the administration console of the CMS, and you know that the user will always have JS on or your site trusted, then you can safely use JS to fill the default value, as per jlbruno.


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

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.


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"); ?>">


The following code works well:

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

Note that this relies on PHP.


HTML

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

JS

$(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;       
    $("#theDate").attr("value", today);
});

demo

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

HTML

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

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


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>

There is no default method within HTML itself to insert todays date into the input field. However, like any other input field it will accept a value.

You can use PHP to fetch todays date and input it into the value field of the form element.

<?php
    // Fetch the year, month and day
    $year = date(Y);
    $month = date(m);
    $day = date(d);

    // Merge them into a string accepted by the input field
    $date_string = "$year-$month-$day";

    // Send to the browser the input field with the value set with the date string
    echo "<input type='date' value='$date_string' />";
?>

The value field accepts the format YYYY-MM-DD as an input so simply by creating a variable $date_string in the same format that the input value accepts and fill it with the year, month and day fetched from todays date and voilá! You have yourself a preselected date!

Hope this helps :)

Edit:

If you would like to have the input field nested within HTML rather than PHP you could do the following.

<?php
    // Fetch the year, month and day
    $year = date(Y);
    $month = date(m);
    $day = date(d);

    // Merge them into a string accepted by the input field
    $date_string = "$year-$month-$day";
?>
<html>
    <head>...</head>
    <body>
        <form>
            <input type="date" value="<?php print($date_string); ?>" />
        </form>
    </body>
</html>

I realise this question was asked a while back (2 years ago) but it still took me a while to find a definite answer out on the internet, so this goes to serve anyone who is looking for the answer whenever it may be and hope it helps everyone greatly :)

Another Edit:

Almost forgot, something thats been a royal pain for me in the past is always forgetting to set the default timezone whenever making a script in PHP that makes use of the date() function.

The syntax is date_default_timezone_set(...);. Documentation can be found here at PHP.net and the list of supported timezones to insert into the function can be found here. This was always annoying since I am in Australia, everything is always pushed back 10 hours if I didn't set this properly as it defaults to UTC+0000 where I need UTC+1000 so just be cautious :)


Simplest working version I tested:

_x000D_
_x000D_
<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>
_x000D_
_x000D_
_x000D_


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());

<input id="datePicker" type="date" />

_x000D_
_x000D_
$(document).ready( function() {_x000D_
    var now = new Date();_x000D_
 _x000D_
    var day = ("0" + now.getDate()).slice(-2);_x000D_
    var month = ("0" + (now.getMonth() + 1)).slice(-2);_x000D_
_x000D_
    var today = now.getFullYear()+"-"+(month)+"-"+(day) ;_x000D_
_x000D_
_x000D_
   $('#datePicker').val(today);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="datePicker" type="date" />
_x000D_
_x000D_
_x000D_


A simple solution:

<input class="set-today" type="date">
<script type="text/javascript">
    window.onload= function() {
        document.querySelector('.set-today').value=(new Date()).toISOString().substr(0,10));
    }
</script>

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().


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!


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

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?