minDate:0 in Jquery DatePicker also disable today's date - javascript

Sorry for posting this simple question. Application is going to be deployed soon, and recently a bug came, but i am not able to figure out why it is comming.
Created A JS_BIN this is the link
http://jsbin.com/razufavuru/1/edit?html,js,output
Error is minDate: 0 is disabling today's date also while i want to disable only past dates.
This is jquery code:
$("#leaveEndDate").datepicker(
{
minDate: 0,
beforeShowDay : disablePublicHolidaysAndWeekends,
minDate : dateToday,
onSelect : function(dateText, inst) {
var firstDate = $("#leaveStartDate").datepicker('getDate');
var selDate = null;
selDate = $(this).datepicker('getDate');
var lastDate = selDate;
if (lastDate < firstDate) {
$("#leaveEndDate").val('');
$("#endDateError").html(
"End Date must be greater than Start Date");
$(inst).datepicker('show');
} else {
$("#endDateError").html("");
calculateDays(firstDate, lastDate);
}
}
});
Disable Holiday and Weekends Method is
function disablePublicHolidaysAndWeekends(date) {
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(day < 10 && day > 0){
day = '0'+day;
}
var getdate = year+ '/' + '0' +(month + 1) + '/' + day;
for (var i = 0; i < publicHolidayDates.length; i++) {
if ($.inArray( getdate ,publicHolidayDates) != -1 || new Date() > date) {
return [ false ];
}
}
var noWeekend = $.datepicker.noWeekends(date);
return !noWeekend[0] ? noWeekend : [ true ];
}
this is the img
public holidays are comming from database.
It confuse me lot when this code for another datapicker works.
$("#targetDate").datepicker({
beforeShowDay : $.datepicker.noWeekends,
minDate : 0
});
Here it do not disable today date.
this is the img

jQuery Datepicker value minDate expect value of type
Type: Date or Number or String
Try minDate: new Date() instead, or minDate: '0'
UPDATE:
What causes your issue is your custom function:
function disablePublicHolidaysAndWeekends(date) {
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(day < 10 && day > 0){
day = '0'+day;
}
if(month < 9 && month > 0){ //added control over month, as you would have got errors for month=10, 11, 12 in the below variable getdate
month = '0' +(month + 1);
}
else{
month += 1;
}
var getdate = year+ '/' + month + '/' + day;
for (var i = 0; i < publicHolidayDates.length; i++) {
//removed "|| new Date() > date"
if ($.inArray( getdate ,publicHolidayDates) !== -1 ) {
return [ false ];
}
}
var noWeekend = $.datepicker.noWeekends(date);
return !noWeekend[0] ? noWeekend : [ true ];
}
Read this about Date comparison in javascript
Fiddle here

Related

convert date format javascript beforeshowday [duplicate]

This question already has answers here:
Reformat string containing date with Javascript
(3 answers)
Closed 5 years ago.
var dates = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["ph"]));
//dates[0] = 16-09-2017
//date = 09/16/2017
$('#StartDate').datepicker({
dateFormat: JsDateFormat,
autoclose: true,
beforeShowDay: function (date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
console.log(date);
return [true, 'ui-state-highlight highlight-red', name[i]];
}
}
return [true];
}
});
how to change the date format from '09/16/2017' to '16-09-2017'?
i had tried
new Date('dd-M-yy', date).toString() - not working
date.toString('dd-M-yy') - not working
Since you're using datepicker you can use $.datepicker.formatDate
Here is a snippet using formatDate to compare the dates in the array:
var dates = ['10-10-2017', '25-10-2017', '29-10-2017'];
$('#StartDate').datepicker({
dateFormat: "d/m/yy",
autoclose: true,
beforeShowDay: function (date) {
for (var i = 0; i < dates.length; i++) {
if (dates[i] == $.datepicker.formatDate('dd-mm-yy', date)) {
console.log(date);
return [true, 'ui-state-highlight highlight-red', name[i]];
}
}
return [true];
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<input type="text" id="StartDate" name="StartDate"/>
ViewData["ph"] the date time will be converted to string with culture of the server in which the application is running so be sure to convert with this format in the server and assign to the ViewData.
If value passed to JsonConvert is a type of Date object then make use of the formating parameter to the method SerializeObject
JsonConvert.SerializeObject(this, Formatting.None, new IsoDateTimeConverter() {
DateTimeFormat = "dd-M-yy" });
If you want to convert date to string refer the answer provide by #rahul mr
for all browsers
function formattedDate(d) {
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return day + '/' + month + '/' + year;
}
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
this function returns date in format you needed

Angularjs start date and end date validations

I am completely New to Angularjs and trying to validate 2 scenarios. I have 2 text boxes one with start date and the other with end date. I am checking
Show validation error on UI if start date is not greater than or equal to today. It should be today or any day after today.
Show validation error on UI if start date is greater than end date. End date should be greater than start date.
I tried the below code which did not work. Any suggestions please.
Html Code
<label for="endDate" class="control-label">Start Date:</label>
<div>
<input type="text" class="form-control"
id="startDate" ng-model="startDate" />
</div>
<label for="text" class="control-label">End Date:</label>
<div>
<input type="text" class="form-control"
id="endDate" ng-model="endDate"
ng-change='checkErr(startDate,endDate)' />
</div>
<span>{{errMessage}}</span>
js code
$scope.checkErr = function(startDate,endDate){
$scope.errMessage = '';
$scope.curDate = new Date();
if(startDate < endDate){
$scope.errMessage = 'End Date should be greate than start date';
return false;
}
if(startDate < curDate){
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
I have input type as text for both date controls.I am using bootstrap date picker.
You have the logic reversed on the first bit and you have to construct a new date from startDate to compare to today's date. Also you set curDate to the scope, $scope.curDate = new Date() but then you were referencing it as curDate without the $scope so it was undefined. Lastly, you need to cast stateDate and endDate to a date as well. Otherwise you're just comparing strings.
$scope.checkErr = function(startDate,endDate) {
$scope.errMessage = '';
var curDate = new Date();
if(new Date(startDate) > new Date(endDate)){
$scope.errMessage = 'End Date should be greater than start date';
return false;
}
if(new Date(startDate) < curDate){
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
Working example: http://jsfiddle.net/peceLm14/
It looks like you're referencing curDate which is undefined. Change the conditional to if (startDate < $scope.curDate). See fiddle for working example http://jsfiddle.net/4ec3atzk/1/
$scope.checkErr = function(startDate,endDate){
$scope.errMessage = '';
$scope.curDate = new Date();
if (startDate < endDate){
$scope.errMessage = 'End Date should be greate than start date';
return false;
}
if (new Date(startDate) < $scope.curDate){
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
$scope.datepickerObjectfromdates = {
todayLabel: 'Today',
closeLabel: 'Close',
setLabel: 'Ok',
setButtonType : 'button-calm',
todayButtonType : 'button-calm',
closeButtonType : 'button-calm',
inputDate: new Date(),
mondayFirst: true,
templateType: 'popup',
showTodayButton: 'true',
modalHeaderColor: 'bar-calm',
modalFooterColor: 'bar-calm',
callback: function (val) {
var getdate = GetFormattedFromDates(val);
$scope.date.FromDates = getdate;
localStorage.date = $scope.FromDates;
},
dateFormat: 'MM-dd-yyyy', //Optional
closeOnSelect: false, //Optional
};
function GetFormattedFromDates(val) {
if(typeof(val)==='undefined')
{
$scope.date.FromDates = '';
}
else {
var todayTime = new Date(val);
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
var year = todayTime.getFullYear();
return day + "/" + month + "/" + year;
}
}
$scope.datepickerObjecttodates = {
todayLabel: 'Today',
closeLabel: 'Close',
setLabel: 'Ok',
setButtonType : 'button-calm',
todayButtonType : 'button-calm',
closeButtonType : 'button-calm',
inputDate: new Date(),
mondayFirst: true,
templateType: 'popup',
allowOldDates: false,
showTodayButton: 'true',
modalHeaderColor: 'bar-calm',
modalFooterColor: 'bar-calm',
callback: function (val) {
var getdate = GetFormattedToDates(val);
$scope.date.ToDates = getdate;
//$scope.date.ToDates = getdate.clear();
},
dateFormat: 'dd-MM-yyyy', //Optional
closeOnSelect: false, //Optional
};
function GetFormattedToDates(val) {
if (typeof(val) === 'undefined') {
$scope.ToDates = '';
}
else {
var todayTime = new Date(val);
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var year = todayTime.getFullYear();
return day + "/" + month + "/" + year;
}
}

Disable holiday, sundays and past dates inside jQuery UI datepicker

I'm in creating appointment form with jQuery datepicker. I've search around but seems that I can't combine all function I want in the beforeshowday.
What I want from the datepicker is disabled all date before today (yesterday and the rest of it because you can't make appointment at date before today it must be later), then disabled on every Sunday (its non working day) and public holiday (this one using array). What I saw from others is the jQuery are specifically for only one function like public holiday it just an array, but how about disabled previous day and sunday?
I tried to follow this articles http://articles.tutorboy.com/2010/09/03/jquery-ui-datepicker-disable-specified-dates/ but I don't know how to combine it. Can someone show me how?
I have this to disabled on every Sunday
function disabledSunday(date) {
var day = date.getDay();
return [(day != 0), ''];
}
$('#datepicker').datepicker({
dateFormat: 'mm-dd-yy',
beforeShowDay: disabledSunday
});
This one for alldates till today
var date = new Date();
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
// Disable all dates till today
$('#datepicker').datepicker({
minDate: new Date(y, m, d),
dateFormat: 'mm-dd-yy',
});
This one is for specific dates such as public holiday
// Disable a list of dates
var disabledDays = ["5-31-2013", "6-01-2013"];
function disableAllTheseDays(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1) {
return [false];
}
}
return [true];
}
$('#datepicker').datepicker({
dateFormat: 'mm-dd-yy',
beforeShowDay: disableAllTheseDays
});
How to combine these three function into one, I'm not much into Jquery and javascript
try this :-
html code :
<input id="txtDate" />
function disabledays(date) {
var ymd = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
//if u have to disable a list of day
var removeDays = ["2013-6-11","2013-6-31" ];
if ($.inArray(ymd, removeDays) >= 0) {
return [false];
} else {
//Show accept sundays
var day = date.getDay();
return [(day == 1 || day == 2 || day == 3 || day == 4 ||day == 5 ||day == 6 )];
}
}
$(function () {
$('#txtDate').datepicker({
beforeShowDay: disabledays
});
});
Try this
$("#datepicker").datepicker({ minDate: 0 });
You can use minDate option to disable past dates. In addition, you can use beforeShowDay option to check the other two conditions**.
$("#datepicker").datepicker({
minDate: 0,
beforeShowDay: function (date) {
// it is possible to write the following function using one line
// of code; instead, multiple if/else are used for readability
var ok = true;
if (date.getDay() === 0) { // is sunday
ok = false;
} else {
var dateStr = $.datepicker.formatDate("m-dd-yy", date);
if ($.inArray(dateStr, disabledDays) >= 0) { // is holiday
ok = false;
}
}
return [ok, ""];
}
});
});
** Actually it is possible to check all three conditions in that function.
May u will find your slution here
http://jqueryui.com/datepicker/#min-max

Hiding days in datepicker

I have some problem with hiding days in datepicker depending of day of week e.g. if today is friday hide saturday and if today is saturday - hide sunday.
I have this code who check what day is today:
$(function () {
var day_date = new Date();
var weekday = new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[day_date.getDay()];
$('#day_of_week').val(n);
});
I also have this code to hide (but whole) weekends and days who always be hidden:
var disabledDays = ['15/8/2012', '1/11/2012', '11/11/2012', '25/12/2012', '26/12/2012'];
function nationalDays(date) {
var m = date.getMonth(),
d = date.getDate(),
y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray(d + '/' + (m + 1) + '/' + y, disabledDays) != -1 || new Date() > date) {
return [false];
}
}
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
On datepicker the line who "execute" above code looks like this:
beforeShowDay: noWeekendsOrHolidays,
I try to do this with this code, but it didn't work:
$('#day_of_week').change(function()
if( $("#day_of_week").val() == Friday ) {
$("#date_from, #date_to").datepicker({
beforeShowDay: noWeekendsOrHolidays
});
}
else {
}
});
I will be very grateful for any help.
I am using a date picker in which it automatically work on hiding date.
I hope it will helpful to you.
http://multidatespickr.sourceforge.net/#maxPicks-demo
I got a link regarding this and hopefull it will work.
http://multidatespickr.sourceforge.net

Showing the next month

I wonder how to set next month with showing only mondays active:
i tried to do smth like that but it wont work
function onlyMondaysNextMonth(date){
var day = date.getDay();
var mDate = date.getMonth() + 1;
return {
minDate: mDate,
}
return [(day == 1),''];
}
Thank you.
Use the following code to enable only Mondays starting from next month
var minDate = null;
var now = new Date();
if (now.getMonth() == 11) {
minDate = new Date(now.getFullYear() + 1, 0, 1);
} else {
minDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
/* create datepicker */
jQuery(document).ready(function () {
jQuery('#datepicker').datepicker({
minDate: minDate,
constrainInput: true,
beforeShowDay: beforeShowDay
});
});
function beforeShowDay(date) {
var day = date.getDay();
if (day == 1)
return [true]
return [false];
}
The working sample is hosted in http://elangovanr.com/samples/jquery/datepickermonday.html for your reference.

Categories

Resources