Disable certain dates from html5 datepicker - html

Is it possible to disable dates when I use
I want to disable current date for one scenario and future dates for other scenario.
How should I disable the dates?

You can add a min or max attribute to the input type=date. The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.
<input name="somedate" type="date" min="2013-12-25">
The min and max attributes must be a full date; there's no way to specify "today" or "+0". To do that, you'll need to use JavaScript or a server-side language:
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("somedate")[0].setAttribute('min', today);
http://jsfiddle.net/mblase75/kz7d2/
Ruling out only today, while allowing past or future dates, is not an option with here. However, if you meant you want tomorrow to be the min date (blanking out today and all past dates), see this question to increment today by one day.
As in all other cases involving HTML forms, you should always validate the field server-side regardless of how you constrain it client-side.

In pure HTML, the only restrictions you can put on dates are its lower and upper bounds through the min and max attributes. In the example below, only the dates of the week I'm posting this question are allowed, other appear greyed out and clicking on them doesn't update the input value:
<input type="date" min="2019-06-02" max="2019-06-08"/>
You can also disable any invalid date by using a few lines of JavaScript, but this doesn't ship with all the native <input type="date"> features like greyed-out dates. What you can do is set the date value to '' in case of an invalid date, an error message could also be displayed. Here is an example of an input that doesn't accept weekend dates:
// Everything except weekend days
const validate = dateString => {
const day = (new Date(dateString)).getDay();
if (day==0 || day==6) {
return false;
}
return true;
}
// Sets the value to '' in case of an invalid date
document.querySelector('input').onchange = evt => {
if (!validate(evt.target.value)) {
evt.target.value = '';
}
}
<input type="date"/>

HTML datepicker (<input type=date>) supports min/max attribute, but it is not widely supported.
At the meantime you may consider using bootstrap-datepicker, v1.2.0 is on github.
References:
W3C spec

You could use this to disable future dates :
Inside you document.ready function, place
//Display Only Date till today //
var dtToday = new Date();
var month = dtToday.getMonth() + 1; // getMonth() is zero-based
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
$('#dateID').attr('max', maxDate);
and in form
<input id="dateID" type="date"/>
Here is the working jFiddle Demo

For react and similar libraries, you may use this to disable all dates before today.
<input type='date' min={new Date().toISOString().split('T')[0]} >

Depending on what you need, you can also use the step attribute to only enable specific dates - e.g. every Monday, or every other day. You can use it in combination with min and max
e.g. every Monday
<input type="date" step="7" value="2022-04-04">
Every Thursday
<input type="date" step="7" value="2022-04-07">
Every other day
<input type="date" step="2">

Related

Bootstrap DatePicker, how to set the start date as next day 12AM?

I was trying to make use of bootstrap date picker, and make the user to select next day or above in the calendar.
How to make the (data-date-start-date="12AM next day") instead of (data-date-start-date="+1d").
To be precise, the selected insurance policy needs be covered from next day 12AM.
I'm banging my head from last couple of days, tried most of the known probabilities.
It needs to be set via Bootstrap date picker! Any help would be highly appreciated.
<div class="input-group date" data-provide="datepicker" data-date-autoclose="true" data-date-start-view="0" data-date-force-parse="false" data-date-start-date="+1d"></div>
Try this:
<script type="text/javascript">
$(function () {
var d = new Date();
d.setDate(d.getDate() + 1); //this will set tomorrow
d.setHours(0, 0, 0, 0); //this will set 12 AM
$('#datetimepicker1').datetimepicker({
defaultDate: d,
});
});
</script>
bootstrap-datepicker is not designed to be concerned with time (search the documentation for the word "time").
There are other libraries that help with picking dates and times.

How to set end date as a current or today's date in angularjs?

all I want to filter the items like (Start and End Date) which are based on invoice_date using the date range functionality in meanjs app.
My problem is the date filter function are working perfectly in plunker and my localHost production but while pushing to server it's showing only up to May month data's if some invoice_date values date has been `2017-08-24 and 2017-07-27' these data is not displaying in table, I don't know where I did the mistake and what I have missed it ..... My Plunk
Please look at my plunker to reference.
I Have displaying invoice_date, so this is the field I want to use for filtering.
So what I exactly looking for, I want to filter the invoice_date as start date and end date : for example:- if we select start date like 24-05-2017 and end date is 24-08-2017 in table this two transaction only need to display or filter... so I have used date range filter to achieve this solution, but in server it's not working for us please help.
In my server if I select end date as today's date all data's are showing perfectly on the table, so I think the problem is based on these fields $scope.from = new Date(2014, 04, 30);
$scope.to = new Date(2019, 08, 25);
So if We set end date as a current or today's date in default, I think
the problem would be solved, so how to set today's date as a default to end date...
Controller:
.filter('dateRange', function() {
return function(records, dateKey, from, to) {
return records.filter(function(record) {
return !moment(record[dateKey], 'YYYY-MM-DD').isBefore(moment(from))
&& !moment(record[dateKey], 'YYYY-MM-DD').isAfter(moment(to));
});
};
})
Html:
<input type="date" class="form-control" name="from" ng-model="from">
<input type="date" class="form-control" name="to" ng-model="to" ng-bind="getDatetime | date:'yyyy-MM-dd'">
Filter:-
ng-repeat="data in record | dateRange : 'invoice_date' : from : to"
I tried the ng-bind method to set default today's date to end date like following:-
In controller:-
$scope.getDatetime = new Date();
In Html:-
<lable>End Date</lable><input type="date" class="form-control" name="to" ng-bind="getDatetime | date:'yyyy-MM-dd'" ng-model="to">
I have created plunker for reference:- My plunker
Showing like the moment is not defined:-

angular bootstrap datetimepicker set available date

I am using a angular bootstrap datetimepicker from https://github.com/dalelotts/angular-bootstrap-datetimepicker.
I want to set the available select day from today and today + 7.
In the order words, disabled all other day.
Any suggestions will be appreciated.
Thanks.
Yes, you can use the before-render callback to disable any dates that are out of range.
There is an example in the demo page.
Something like this should work (not tested at all)
function renderOnBeforeRender($dates) {
var now = moment.valueOf();
var max = moment().add('day', 7).valueOf();
angular.forEach($dates, function (dateObject) {
dateObject.selectable = (dateObject.localDateValue() >= now && dateObject.localDateValue() <= max)
});
}

HTML5 Time Element in Form with Milliseconds

There are several examples of HTML5 form options on this page, including the "time" element. Is it possible to force the time element to include a millisecond component?
I'm not concerned for the fallback option where a plain text box is used.
This works:
<input type="time" step="0.001"></input>
Live preview: http://jsbin.com/giqikelumu/edit?html,output
Simply use the step attribute. In case of a input type="time". The step attribute defaults to 60 (1 means 1 second). But you can also set fractions.
<input type="time" step="any" />
As its an input tag, the value can be entered into it by the user then using the step attribute as stated above will surely help.
What if this input is in the form and value can come from some API cal and is given to the form to show it. It can be changed too. If the requirement then is to show or not show the second or millisecond part we can do the following.
When second and millisecond is required
getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
if (val != undefined) {
date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
}
}
When second and millisecond is NOT required
getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
if (val != undefined) {
date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes());
}
}

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?
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"
Use HTMLInputElement.prototype.valueAsDate:
document.getElementById('datePicker').valueAsDate = new Date();
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();
This relies upon PHP:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
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.
Follow the standard Y-m-d format, if you are using PHP
<input type="date" value="<?php echo date("Y-m-d"); ?>">
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;
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>
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>
HTML:
<input type="date" value="2022-01-31">
PHP:
<input type="date" value="<?= date('Y-m-d') ?>">
Date format must be "yyyy-mm-dd"
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());
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.
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>
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().
<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" />
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>
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.
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'); ?>" />
For NodeJS (Express with SWIG templates):
<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />
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
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!
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">
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"); ?>">
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" />
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" />
To match the original query.
date.value = new Date().toJSON().split('T')[0]
<input type="date" id="date"/>
by Javascript:
var today = new Date();
document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
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 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'
});
}