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.
<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>
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>
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.
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);
});
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;
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') %>" />
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