449

Given an input element:

<input type="date" />

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

Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
Ian Brown
  • 4,491
  • 2
  • 12
  • 4

35 Answers35

330

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"
Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
Tak
  • 10,344
  • 5
  • 26
  • 47
242

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();
Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
brianary
  • 7,906
  • 2
  • 33
  • 29
  • 1
    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. – Ben Clayton Mar 27 '13 at 14:41
  • @BenClayton I wonder if that would be mitigated by assigning the current date to defaultValue. Is it still a problem? – brianary Dec 28 '13 at 05:35
  • Using `.toJSON` [doesn't account for timezone offset](http://stackoverflow.com/questions/11382606/javascript-date-tojson-dont-get-the-timezone-offset). – Web_Designer Dec 30 '13 at 01:03
  • 1
    @Web_Designer Fair enough. You'll want to adjust with `local.setMinutes(this.getMinutes() - this.getTimezoneOffset());` (as that answer eventually gets to) first, then. – brianary Dec 30 '13 at 23:26
  • 1
    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. – RobG Sep 10 '15 at 04:35
  • @RobG OK, I can see where `toISOString` would be a little more explicit. Obviously, if you are building a form that could be reset (is that common anymore?), you'd want to set the `defaultValue` property as well. – brianary Sep 10 '15 at 04:45
  • Setting a *defaultValue* property or attribute doesn't update the actual default value. That can only be done by setting the *value* attribute, either inline or using *setAttribute*. I have no idea why many web developers don't provide reset buttons, they are very useful. I suspect it's because they have issues coding for them and it's easier to just leave them off the form. – RobG Sep 10 '15 at 05:22
  • @RobG Incorrect. There is no `defaultValue` attribute, but there has been a `defaultValue` property on inputs since there was a JavaScript. It's initially the value of the `value` attribute in the markup, but it's also read/write. Test it: https://jsfiddle.net/p0x7c9fx/ I suspect the reason reset buttons have fallen out of fashion is that it's too easy to lose too much data in a large form, and no particular benefit for a small form over the more intentional **×** now at the end of fields. People tended to click them by mistake. I've never heard of issues coding for them. – brianary Sep 10 '15 at 15:08
  • I didn't say there was a standard *defaultValue* attribute, I said that setting one doesn't (necessarily) affect the default value. I was incorrect that setting the *defaultValue* property doesn't affect the defaultValue (I've actually never used it for that). Much of this was browser dependent until HMTL 5 so I developed methods that work everywhere and kept using them because they still work everywhere. Almost every form I've had anything to do with design–wise has a reset button, sometimes they're omitted where the intention is to deliberately not provide a simple way to remove the content. – RobG Sep 10 '15 at 22:38
  • @RobG The `defaultValue` property has always worked across all browsers, while `setAttribute` doesn't for older IEs or most pre-XHTML browsers. – brianary Sep 10 '15 at 22:52
  • I don't have enough old browsers to test that, I've always set the attribute and property since that reliably achieves the required result. I suppose setting the *defaultValue* property is an alternative to setting the *value* attribute, but it's a roundabout way of doing it. – RobG Sep 11 '15 at 02:51
  • @RobG I wouldn't suggest them as alternatives. Set the `value` usually, but set the `defaultValue` if you need to support a form reset and establish an initial value that differs from the markup. – brianary Sep 11 '15 at 03:01
  • This pure JS example doesn't work for me. Andre's version works perfectly. It needs to be .valueAsDate, not .value, and you've gotta lose the .toDateInputValue(), you want the new Date() object itself returned. – apraetor Nov 15 '16 at 17:18
  • @apraetor Why didn't it work for you? How well is valueAsDate supported by browsers? It seems eventually optimal, but still really new. – brianary Nov 15 '16 at 17:36
  • @brianary It doesn't work because `Date().toDateInputValue()` isn't a valid method. The HTML5 `datePicker` isn't supported in all browsers (Firefox, for example) but in those that support it, `.valueAsDate()` is available. Doesn't work: https://jsfiddle.net/apraetor/7Lyg9w1c/5/ Works: https://jsfiddle.net/243tdkox/ – apraetor Nov 17 '16 at 22:45
  • @apraetor You didn't define it first with the prototype as described. Add the first code block to define that method. – brianary Nov 17 '16 at 22:48
  • @brianary Good call, my bad. Either way, this solution only works on browsers with HTML5 support for datePicker, and they will all support `.valueAsDate`, so why reinvent the wheel here? – apraetor Nov 17 '16 at 22:54
  • 1
    @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. – brianary Nov 17 '16 at 23:01
  • I like this except for the fact that you modify an internal. I'd make it a function of its own. – ADJenks Jan 25 '19 at 22:05
  • @rovyko There's really no reason to use `valueAsNumber`. As discussed earlier, `valueAsDate` works for newer browsers without the need for anything complicated. – brianary Feb 16 '19 at 23:19
  • 2
    This answer worked for me using a `input[type=datetime-local]` and changing it to `slice(0,19)` HTH – jcruz Nov 22 '19 at 13:31
  • I would strongly recommend against adding this functionality onto the Date prototype itself. It has the same effect as creating a global. Rather create a function locally or a class. – Caveman Feb 17 '20 at 13:47
  • Pure JS example should be something like: `document.querySelector('input[type="date" i]').valueAsDate = new Date()` – Jose Serodio Apr 20 '21 at 18:24
  • Something like this will change any input type date found to actual date: `document.querySelectorAll('input[type="date" i]').forEach(input => input.valueAsDate = new Date())` – Jose Serodio Apr 20 '21 at 18:25
  • @JoseSerodio True, though I'm not sure how often you'd want to set every date input to today rather than specific inputs, but that's a good way to do it. – brianary Apr 20 '21 at 18:31
  • 1
    @brianary As you seem interested, I just wrote this because I'll be using it. In my case, I'm defaulting to the actual date (I'm building a form for repairing techinicians).. first input date will be the received device date, and second will be the expected date to be repaired. Hopefully it will be repaired within the same day... so this will save two clicks! – Jose Serodio Apr 20 '21 at 18:40
  • @JoseSerodio Sounds good! Just not for birthday fields, maybe. Old people like me end up scrolling forever! ;) – brianary Apr 20 '21 at 18:43
221

Use HTMLInputElement.prototype.valueAsDate:

document.getElementById('datePicker').valueAsDate = new Date();
Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
André
  • 7,854
  • 1
  • 21
  • 23
  • 1
    is it working in all browsers ? and mobile versions as well ? Tested ? – Usman Younas Apr 15 '15 at 10:53
  • 2
    @UsmanY It's part of the HTML5 spec, so anything that supports HTML5 input types should support `valueAsDate`. https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate – wersimmon May 20 '15 at 15:13
  • 1
    @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? – brianary Nov 15 '16 at 17:47
  • 4
    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 https://austinfrance.wordpress.com/2012/07/09/html5-date-input-field-and-valueasdate-timezone-gotcha-3/ – Aupajo Mar 28 '18 at 00:48
  • 1
    As @Aupajo said, this sets the wrong date if you don't want UTC time. – ADJenks Jan 24 '19 at 01:59
103

This relies upon PHP:

<input type="date" value="<?php echo date('Y-m-d'); ?>" />
Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
Isham Mohamed
  • 1,169
  • 1
  • 7
  • 2
  • 74
    Your answer depends on php completely. – Yëco Nov 06 '12 at 22:04
  • 1
    If you're contact form is on a PHP page (for example, on a WordPress page or shortcode), this works perfectly. Many thanks Isham! – tristanojbacon Nov 14 '12 at 15:34
  • 5
    You could reduce redundancy by changing `` to `` – Murray Rowan Jan 21 '13 at 18:21
  • 7
    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. – Jukka K. Korpela May 29 '13 at 07:13
  • 2
    you can also use short tag = date('Y-m-d'); ?>. One "echo" less – sashok_bg Sep 17 '15 at 09:12
  • I feel the need to reiterate since jukka only has 6 upvotes and it's serious. Again, like Jukka states, the date will be of the server, which most servers, I assume, are defaulted to SYSTEM or UTC. If you're anywhere in the world where you're in a different offset from the system or UTC, you may be getting the wrong date. – Govind Rai Sep 20 '16 at 05:10
40

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.

Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
Jeff
  • 3,989
  • 21
  • 32
  • In Opera (tested on Opera 12 / Windows) this doesn't work if you don't put the leading zeros in month and day. – Renato Jul 03 '12 at 06:01
31

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

<input type="date" value="<?php echo date("Y-m-d"); ?>">
Kiran Reddy
  • 634
  • 11
  • 26
Shuhad zaman
  • 2,298
  • 22
  • 25
26

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>
Jukka K. Korpela
  • 178,198
  • 33
  • 241
  • 350
  • 6
    Or if you want it to be Y10K compliant: `= new Date().toISOString().split('T')[0];` – Blazemonger Jan 30 '14 at 19:36
  • 2
    [*toISOString*](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-date.prototype.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. – RobG Sep 10 '15 at 05:11
25

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 +"T00:00";       
    $("#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 +"T00:00";       
document.getElementById("theDate").value = today;

##demo

22

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>
Gabriel Garcia
  • 912
  • 9
  • 11
  • 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. – secretwep Jun 29 '18 at 22:21
15

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());
MD Iyasin Arafat
  • 654
  • 9
  • 22
11

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.

Umair Khalid
  • 1,961
  • 1
  • 18
  • 25
9

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

dipenparmar12
  • 1,314
  • 1
  • 11
  • 25
Gowtham Ag
  • 167
  • 2
  • 5
7
<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" />
Santanu
  • 119
  • 1
  • 5
7

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>
Zaffer
  • 137
  • 1
  • 10
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>
Blazemonger
  • 82,329
  • 24
  • 132
  • 176
teshguru
  • 3,345
  • 1
  • 16
  • 6
6

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 minutes per millisecond).

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

rovyko
  • 3,053
  • 2
  • 19
  • 35
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'); ?>" />
Tom Fenech
  • 65,210
  • 10
  • 85
  • 122
user2615287
  • 81
  • 1
  • 2
5

For NodeJS (Express with SWIG templates):

<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />
CodeValve
  • 87
  • 1
  • 5
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
Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
Dexygen
  • 11,681
  • 11
  • 73
  • 144
  • You should state which property of an input element to assign it to. `value` or `valueAsDate`? Looks good though. – ADJenks Jan 24 '19 at 17:55
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!

Oliver
  • 21,908
  • 4
  • 55
  • 73
Gumba
  • 41
  • 4
  • 1
    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. – Shiva May 28 '14 at 13:09
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"); ?>">

csandreas1
  • 1,870
  • 19
  • 36
2

by Javascript:

var today = new Date();

document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
Charnstyle
  • 93
  • 7
2
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
Sebastian Lenartowicz
  • 4,340
  • 4
  • 24
  • 36
kingsuede
  • 21
  • 1
2

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>
reformed
  • 3,922
  • 9
  • 51
  • 77
gajam
  • 357
  • 2
  • 9
  • 1
    @GeorgeJempty This does not if the current time in UTC is a different day than the current day. It will return the current date in UTC, not in your local time zone. – ADJenks Jan 24 '19 at 01:52
  • @adjenks Heh I see that it was a perfect time for me to test, 10 minutes until midnight – Dexygen Jan 24 '19 at 05:50
  • @adjenks I finally whipped out a half-dozen lines that avoid the UTC pitfall and improves slightly on a couple of existing similar jQuery/non-ES6 answers: https://stackoverflow.com/a/54341296/34806 – Dexygen Jan 24 '19 at 07:24
  • Answer has an extra ")" at end of line, and extraneous parends around "new Date()". Should be: `document.querySelector('.set-today').value=new Date().toISOString().substr(0,10);` – Kirby L. Wallace Apr 06 '20 at 01:30
2

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"  />
StefaDesign
  • 650
  • 6
  • 15
  • This is way too cumbersome for just needing to use a default value. – reformed Mar 13 '20 at 16:43
  • 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.... – StefaDesign Mar 28 '20 at 00:53
1

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') %>" />
Sean
  • 227
  • 4
  • 9
1

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;
Faisal E.K
  • 23
  • 2
1
$(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);
Paul Roub
  • 35,100
  • 27
  • 72
  • 83
Prabha
  • 216
  • 3
  • 16
0

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!

Blazemonger
  • 82,329
  • 24
  • 132
  • 176
Ryan Dunphy
  • 629
  • 2
  • 8
  • 26
0

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>
Nikhil sHETH
  • 420
  • 4
  • 10
  • 3
    Please, please, please don't use document.write in real applications - there are so many problems with using it. – Peter Hart Oct 22 '13 at 15:14
  • Peter, can u explain what prob. u got ? – Nikhil sHETH Oct 24 '13 at 05:23
  • Peter, also mention how u get current date as default value in input type=date – Nikhil sHETH Oct 24 '13 at 05:24
  • 1
    It's not that it doesn't work, but that in general it is bad practice to use document.write. There's a myriad of reasons why this is the case, here are some examples: http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice If I absolutely had to do this in javascript on the client, I'd use an id on the element and document.getElementById to get the element and change it, similarly to some of the other answers on this page. – Peter Hart Oct 25 '13 at 15:05
0

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.

Sean Owen
  • 63,876
  • 22
  • 135
  • 169
Marlon
  • 1
0

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 :)

SteppingHat
  • 1,078
  • 2
  • 20
  • 43
0

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" />
T J
  • 40,740
  • 11
  • 73
  • 131
0

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.

stslavik
  • 2,690
  • 2
  • 17
  • 31
-1

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;
Sandeep
  • 1,474
  • 6
  • 20
  • 32
KapteinMarshall
  • 480
  • 6
  • 19