Ian Brown
Ian Brown

Reputation: 5901

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

Given an input element:

<input type="date" />

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

Upvotes: 590

Views: 1485893

Answers (30)

rovyko
rovyko

Reputation: 4577

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.

Upvotes: 7

EduOK
EduOK

Reputation: 121

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

You can get and set the date value in JavaScript with the HTMLInputElement value and valueAsNumber properties. For example:

const dateControl = document.querySelector('input[type="date"]');
dateControl.value = "2017-06-01";
console.log(dateControl.value); // prints "2017-06-01"
console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp 

Upvotes: 0

AQuirky
AQuirky

Reputation: 5236

Among the more than 30 answers, I didn't see mine here...

let d0 = new Date();
let s0 = `${d0.getFullYear()}-${new String(d0.getMonth() + 1).padStart(2,'0')}-${new String(d0.getDate()).padStart(2,'0')}`;
$('input[name="start_date"]').val(s0);

Upvotes: 0

brianary
brianary

Reputation: 9322

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

Upvotes: 283

Karl Horky
Karl Horky

Reputation: 4924

Use the new Temporal proposal (see browser support below) with a PlainDate object:

<input type="date" class="date-today" />
const today = Temporal.Now.plainDateISO().toString(); // '2023-08-25'
document.querySelector('.date-today') = today;

Or, setting a specific date:

const date = Temporal.PlainDate.from({ year: 2006, month: 8, day: 24 }).toString(); // '2006-08-24'
document.querySelector('.date-today') = date;

If you use React (CodeSandbox Demo):

{/* Today */}
<input
  type="date"
  defaultValue={
    Temporal.Now.plainDateISO().toString()
  }
/>

{/* Specific date */}
<input
  type="date"
  defaultValue={
    Temporal.PlainDate.from({ year: 2006, month: 8, day: 24 }).toString()
  }
/>

Browser Support

Temporal proposal on Can I use shows lacking support for now (no browsers supporting this as of Aug 2023). So unless this changes by the time you do this, you will need to install @js-temporal/polyfill and apply the polyfill like this:

import { Temporal, Intl, toTemporalInstant } from '@js-temporal/polyfill';
Date.prototype.toTemporalInstant = toTemporalInstant;

Upvotes: 2

user3221512
user3221512

Reputation: 214

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

Upvotes: 6

Ichinga Samuel
Ichinga Samuel

Reputation: 96

To match the original query.

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

Upvotes: 4

Okiemute Gold
Okiemute Gold

Reputation: 548

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>

Upvotes: 3

Davide
Davide

Reputation: 1703

HTML:

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

PHP:

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

Date format must be "yyyy-mm-dd"

Upvotes: 29

You can generate the date in the right format like so:

const date = new Date().toLocaleDateString('en-CA')

and then assign it to your input element. In case you're using vue.js you can just do:

<input type="date" :value="date">

Upvotes: 0

jpgerb
jpgerb

Reputation: 1120

Just for the sake of something new/different - you could use php to do it..

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

Upvotes: 0

user2985029
user2985029

Reputation:

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;

Upvotes: 36

R...
R...

Reputation: 2570

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'
    });
}

Upvotes: 3

BendaThierry.com
BendaThierry.com

Reputation: 2110

Nowadays, we should not use anymore moment.js but day.js to handle that without any side-effect. Moment.js was great, but it is not pushing forward, and it is relatively big but was very useful. day.js has good feature enough to be the new candidate to use for future years.

let now = dayjs(); /* same as now = dayjs(new Date()); */

Upvotes: 0

Jeff
Jeff

Reputation: 4146

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.

Upvotes: 49

Isham Mohamed
Isham Mohamed

Reputation: 1679

This relies upon PHP:

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

Upvotes: 150

Andr&#233;
Andr&#233;

Reputation: 9112

Use HTMLInputElement.prototype.valueAsDate:

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

Upvotes: 320

Tak
Tak

Reputation: 11704

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"

Upvotes: 401

Dexygen
Dexygen

Reputation: 12561

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

Upvotes: 5

T J
T J

Reputation: 43156

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

Upvotes: 3

Zaffer
Zaffer

Reputation: 1809

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>

Upvotes: 12

Prabha
Prabha

Reputation: 273

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

Upvotes: 1

gajam
gajam

Reputation: 515

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>

Upvotes: 2

Gowtham Ag
Gowtham Ag

Reputation: 187

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

Upvotes: 10

Faisal E.K
Faisal E.K

Reputation: 23

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;

Upvotes: 1

StefaDesign
StefaDesign

Reputation: 959

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

Upvotes: 3

csandreas1
csandreas1

Reputation: 2378

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

Upvotes: 4

MD Iyasin Arafat
MD Iyasin Arafat

Reputation: 763

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

Upvotes: 23

Santanu
Santanu

Reputation: 151

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

Upvotes: 8

Shuhad zaman
Shuhad zaman

Reputation: 3390

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

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

Upvotes: 37

Related Questions