I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/
I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.
I tried to do something with beforeShowDay option :
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = '';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
but it only "disables" all Sundays whereas I want to remove / hide them:
Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/
EDIT:
Updated fiddle with #Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/
You could do it with just a little CSS but it does leave a gap:
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
Hope this helps a little.
You need do changes in two functions in your daterangepicker.js file:
createMonthHTML()
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
In this function i have added class hideSunday while pushing the element.
The 2nd function is getWeekHead():
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
In this file, I have added class to week-7 header.
CSS:
.hideSunday{display:none;}
Please note, I have not checked all the scenario but it will do trick for you.
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
Moment.js - Get all mondays between a date range
Moment.js: Date between dates
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as dayNumber parameter) in the date range you selected:
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
Then I call this function in my code like that:
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with sundays.length), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and Xfor X sundays in the period):
Finally, here's the working fiddle: https://jsfiddle.net/maximelafarie/dnbd01do/21/
I want to thank any person that helped me. The question was hard to explain and to understand.
You can also do it by setting a custom css class and use it in beforeShowDay like below
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
But it only hides the sundays beginning from current day.
Here is a working fiddle
https://jsfiddle.net/dnbd01do/16/
Related
Does the p:calendar component in Primefaces support sorting the year dropdownlist? By default, it is sorted by ascending, but how about if I want to sort it by descending? I've tried to implement it by using javascript but unfortunately the sort was gone after I selected an option in the dropdownlist.
You can use yearrange attribute. But you need to change/override something to make it works.
I see Primefaces calendar which is using datepicker and datepicker just support yearrange ascending. So I think you can do like that.
<p:calendar yearrange="2027:2017"... />
And override something that datapicker can support new yearrange, like (just my short sample)
$.datepicker._generateMonthYearHeader = function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for (month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if (!inst.yearshtml) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
var startYear = determineYear(years[0]);
var absoluteEndYear = determineYear(years[1]);
if (startYear <= absoluteEndYear) {
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
} else {
for (; startYear >= absoluteEndYear; startYear--) {
inst.yearshtml += "<option value='" + startYear + "'" +
(startYear === drawYear ? " selected='selected'" : "") +
">" + startYear + "</option>";
}
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>";
return html;}
Or you can write or extends more p:calendar component.
Hope that helps.
I have a time/date converter. When the user enters "130" for example it returns "06/07/2016 01:30:00" when they enter "6 7 16" for example it returns "06/07/2016 00:00:00" but when the user enters "6 7 16 130" for example it returns "06/07/2016 false:00"
Here is my relevant code (can show more if need be):
function checkDateTime(val) {
var nowDate = new Date();
var month, day, year, time;
var ar;
if (eval(val)) {
var tval = val.value;
ar = tval.split(' ');
if (ar.length === 3) { // i.e. if it's supposed to be a date
ar[0] = month;
ar[1] = day;
ar[2] = year;
document.getElementById("FromDate").value = CheckDate(val) + ' ' + '00:00:00';
//checkDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]);
}
//alert(LeftPadZero(ar[0]) + ' ' + LeftPadZero(ar[1]) + ' ' + LeftPadZero(ar[2]));
//alert(CheckDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]));
if (ar.length === 1) { // if it's a time
ar[0] = time;
var MM = nowDate.getMonth() + 1;
var DD = nowDate.getDate();
var Y = nowDate.getFullYear();
var nowDateFormat = LeftPadZero(MM) + '/' + LeftPadZero(DD) + '/' + Y;
alert(ar[0]);
document.getElementById("FromDate").value = nowDateFormat + ' ' + checktime(val) + ':00';
}
if (ar.length === 4) { // if date and time
ar[0] = month;
// alert(ar[0]);
ar[1] = day;
// alert(ar[1]);
ar[2] = year;
// alert(ar[2]);
ar[3] = time;
// alert(ar[3]);
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
// alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
}
}
}
function CheckDate(theobj) {
var isInvalid = 0;
var themonth, theday, theyear;
var arr;
if (eval(theobj)) {
var thevalue = theobj.value;
arr = thevalue.split(" ");
if (arr.length < 2) {
arr = thevalue.split("/");
if (arr.length < 2) {
arr = thevalue.split("-");
if (arr.length < 2) {
isInvalid = 1;
}
}
}
if (isInvalid == 0) {
themonth = arr[0];
theday = arr[1];
if (arr.length == 3) {
theyear = arr[2];
} else {
theyear = new Date().getFullYear();
}
if (isNaN(themonth)) {
themonth = themonth.toUpperCase();
//month name abbreviation array
var montharr = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
for (i = 0; i < montharr.length; i++) {
//if the first 3 characters of month name matches
if (themonth.substring(0, 3) == montharr[i]) {
themonth = i + 1;
break;
}
}
} else {
if (themonth < 1 || themonth > 12) {
isInvalid = 1;
}
}
}
if (isNaN(themonth) || isNaN(theday) || isNaN(theyear)) {
isInvalid = 1;
}
if (isInvalid == 0) {
var thedate = LeftPadZero(themonth) + "/" + LeftPadZero(theday) + "/" + LeftPadZero(theyear);
return thedate;
} else {
return false;
}
}
}
function checktime(x) {
var tempchar = new String;
tempchar = MakeNum(x);
if (tempchar != '' && tempchar.length < 4) {
//e.g., if they enter '030' make it '0030'
if (tempchar.length == 3) {
tempchar='0' + tempchar;
}
//e.g, if they enter '11' make it '1100'
if (tempchar.length == 2) {
tempchar=tempchar + '00';
}
//e.g, if they enter '6' make it '0600'
if (tempchar.length == 1) {
tempchar='0' + tempchar + '00';
}
}
if (tempchar==null || tempchar == '') {
return false;
}
else {
if (tempchar=='2400') {
return false;
}else{
var tempnum= new Number(tempchar);
var swmin = new Number(tempnum % 100);
var swhour = new Number((tempnum-swmin)/100);
if (swhour < 25 && swmin < 60) {
x = LeftPadZero(swhour) + ":" + LeftPadZero(swmin);
return x;
}
else {
return false;
}
}
}
return false;
/*
if(eval(changecount)!=null){
changecount+=1;
}
*/
}
function MakeNum(x) {
var tstring = new String(x.value);
var tempchar = new String;
var f = 0;
for (var i = 0; i < tstring.length; i++) {
// walk through the string and remove all non-digits
chr = tstring.charAt(i);
if (isNaN(chr)) {
f=f;
}
else {
tempchar += chr;
f++;
}
}
return tempchar;
}
I have tried numerous things to figure out why the time element returns false in an array of length 4, but not an array length 1 for some reason, including setting various alerts and checking the console. I have googled this problem several times and came up empty.
To reiterate, my problem is that the time element returns false in an array of 4, and what I am trying to accomplish is for the user to input a date and time and have them both formatted and displayed correctly.
Can anybody help and/or offer any advice and/or suggestions? Thanks!
Edit: user enters '130' should convert to '06/07/2016(today's date) 01:30:00'
6 7 16 should convert to '06/07/2016 00:00:00'
6 7 16 130 should convert to '06/07/2016 01:30:00'
There seems to be some missing parts here... various functions and whatever input type these ones need are excluded from your post... However, taking a guess, I'm going to say that when you are making your final "checktime" call, rather than passing the full "val" variable, you should just be passing the last chunk of your split input, "ar[3]" in this case. That way, only that piece is evaluated by the function.
IE:
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
should be
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(ar[3]) + ':00';
Again, this is just a guess due to the missing pieces.
Edit:
After getting some additional details, the issue DOES seem to be in the data being sent to the checktime function, however, due to the current code setup, the fix is actually just making sure that the data being processed by the checktime function is only the last item in the array... see below for the correction within the checktime function:
tempchar = MakeNum(x);
becomes
tempchar = MakeNum(x).split(' ').pop();
I have a datepicker. I want to increment the date by 1 day as mouse wheel up is fired and decrement the date by 1 day as mouse wheel down is fired (upto the minimum possible date).
Below is my code snippet:
HTML
<input type="text" id="txtFromDate" class="calender"/>
JS
$(document).ready(function(){
$("#txtFromDate").datepicker({
minDate: new Date()
});
$("#txtFromDate").datepicker("setDate", new Date()); });
$('.calender').bind('mousewheel DOMMouseScroll', function (event) {
$id = $(this).attr('id');
$minDate = $('#' + $id).datepicker("option", "minDate");
$minDate = ($minDate.getMonth() + 1) + "/" + $minDate.getDate() + "/" + $minDate.getFullYear();
$datePickerDate = $('#' + $id).datepicker("getDate");
$datePickerDate = ($datePickerDate.getMonth() + 1) + "/" + $datePickerDate.getDate() + "/" + $datePickerDate.getFullYear();
var days = parseInt("1", 10);
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
$datePickerDate = new Date($datePickerDate);
$datePickerDate = $datePickerDate.setDate($datePickerDate.getDate() + days);
}
else {
if ($datePickerDate >= $minDate && $('#' + $id ).val() != "") {
$datePickerDate = new Date($datePickerDate);
$datePickerDate = $datePickerDate.setDate($datePickerDate.getDate() - days);
}
}
alert($datePickerDate);
$('#' + $id).val($datePickerDate);
$('#' + $id).datepicker("setDate", $datePickerDate);
});
But the $datePickerDate value is coming to be as 1464028200000.
Here is the Non-Working Demo
What am I doing wrong?
the IsDateValid function below validates date in an american format.What do i change to convert it to validate the date in a European format. when the validate works a user is able to enter the date by simply entering a + or - sign depending on what they want i.e. a past date, or a future date.
function IsLeapYear(year) {
//Convert from string to number
year = year - 0;
if ((year/4) != Math.floor(year/4)) return false;
if ((year/100) != Math.floor(year/100)) return true;
if ((year/400) != Math.floor(year/400)) return false;
return true;
} //function IsLeapYear...
function countChar(str, daChar) {
//See how many of 'dachar' are in 'str' and return as daCount
var daCount=0;
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == daChar)
//increment count each time we find daChar in str
daCount++;
}
return daCount;
} //function countChar...
function IsDateValid(dateField, noDateRqrd) {
//If no date is required and they didn't enter one, then go back
if (((typeof noDateRqrd != "undefined") && (dateField.value.length == 0))||dateField.value.length == 0)
return null;
//We're going to check this date so go on
var GoodLength = false;
var msg='';
var daysOfMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysOfMonthLY = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//Make sure they have the right number of '/'
var cCount=countChar(dateField.value,'/');
//force a date value
if (dateField.value.length >= 3) {
//alert('cc: ' + cCount + 'fl: ' + dateField.value.length);
if ((cCount == 1) && (dateField.value.length >= 3) && (dateField.value.length <= 5))
GoodLength=true;
else if ((cCount == 2) && (dateField.value.length >= 4) && (dateField.value.length <= 10))
GoodLength=true;
}
//If the length is good, then let's check the contents of the dateField
if (GoodLength == true) {
var firstslash=dateField.value.indexOf('/')+1; //must add 1 to get real position
var lastslash=dateField.value.lastIndexOf('/')+1;
/****************************
Note: substr is not included in CFStudio so 'substr' will not be bolded & blue
*****************************/
var month=dateField.value.substr(0,firstslash-1);
if ((!isNaN(month)) && (month < 13)){
if (firstslash != lastslash) {
//alert(dateField.value);
var day=dateField.value.substr(firstslash,lastslash-firstslash-1); //lastslash-firstslash+1
//We only need to tell it where to cut off the first char
var year=dateField.value.substr(lastslash);
//Access dates can range from 100 to 9999.
//SQL Server dates can range from 1753 to 9999.
//Since this code can run for either db, we'll use the more restrivtive date of 1753.
//The length test will catch any date > 9999.
if (!isNaN(day)&&!isNaN(year)&&(year.length < 5)){
//If there isn't a year value, then put in the current year
if (year.length == 0) {
//There is no year so we only need to get day
var day=dateField.value.substr(firstslash,lastslash-firstslash-1);
//Since they didn't enter a year, we'll use the current year
var now = new Date();
year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else if ((year.length == 1) || (year.length == 2)) {
var tmpDate = new Date(dateField.value);
//Programmer's Note: entered value of "00" would be return as "1900" by getFullYear
tmpDate_yyyy = tmpDate.getFullYear()-1900; //Get 4 dig date and reindex without centuary
//alert('tmpDate_yyyy: ' + tmpDate_yyyy);
if (tmpDate_yyyy < 100) { //If less than 100, then we're in 20th centuary
if (tmpDate_yyyy < 60) //do 00 to 59 as 20xx
tmpDate.setFullYear(2000 + tmpDate_yyyy); //reset year to 21st centuary
else //do 60 to 99 as 19xx
tmpDate.setFullYear(1900 + tmpDate_yyyy); //reset year to 20th centuary
//Have to do it the hard way or we'll also get day, time, etc. which we don't want here
//getMonth is zero based so it returns a number one less that we want
}
dateField.value = tmpDate.getMonth()+1 + "/" + tmpDate.getDate() + "/" + tmpDate.getFullYear();
} else if ((year.length == 4)&&(year > 1752)) {
dateField.value = day + "/" + Month + "/" + year;
} else {
msg= 'The date you entered is not valid: ' + dateField.value + '.';
}//if
} else {
msg= 'The date you entered is not valid: ' + dateField.value + '.';
} //if
} else {
//There is no year so we only need to get day
var day=dateField.value.substr(firstslash);
if (!isNaN(day)) {
//Since they didn't enter a year, we'll use the current year
var now = new Date();
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else {
msg= 'The day you entered is not valid: ' + dateField.value + '.';
} //if
}
//alert('m: ' + month + ' d: ' + day + ' y:' + year);
if ((day==0)||(IsLeapYear(year) && day > daysOfMonthLY[month-1])||(!IsLeapYear(year) && day > daysOfMonth[month-1]))
msg= 'The date you entered is not valid: ' + dateField.value + '.';
} else {
msg='The month you entered is not valid: ' + month + '.';
}
} else {
if (dateField.value.length == 0) {
msg= 'You must enter enter a valid Date.';
} else if ((dateField.value.toLowerCase() == 'today')||(dateField.value.toLowerCase() == 'now')) {
var now = new Date();
var day=now.getDate();
var month=now.getMonth()+1; //Have to add 1 to get correct month
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else if ((dateField.value.indexOf('+') == 0)||(dateField.value.indexOf('-') == 0)) {
//alert('in: ' + dateField.value + ', NaN: ' + isNaN(dateField.value));
if (!isNaN(dateField.value)) {
var now = new Date();
var nowMS = now.getTime(); //Get the current time in milliseconds
//Add the number of milliseconds in a day times the number of days requested
//Use the Math.floor to make sure we only get whole days in case they add a decimal value
now.setTime(nowMS + Math.floor((dateField.value * 1000*60*60*24)));
var day=now.getDate();
var month=now.getMonth()+1; //Have to add 1 to get correct month
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else
msg= 'The proper format, +#, or -#, with no spaces in between: e.g., "+6", or "-2". You entered: "' + dateField.value + '".';
} else
msg= '146: The date you entered is not valid: "' + dateField.value + '".';
}
if(msg.length > 0) {
if (typeof noDateRqrd == 'undefined') {
var lastLine="Select 'OK' to re-enter value, or 'Cancel' to enter the current date.\n\n"
} else {
var lastLine="Select 'OK' to re-enter value, or 'Cancel' to clear the date.\n\n"
}
var conmsg ="\n\n____________________________________________________\n\n" +
msg +
"\n\n____________________________________________________\n\n" +
"A valid date must contain at least one forward slash '/' as well as a day and a month.\n" +
"If you leave the year blank, then the current year will be inserted.\n\n" +
"The allowable date range is from 1/1/1753 to 12/31/9999.\n\n" +
lastLine
if (confirm(conmsg))
dateField.focus();
else {
if (typeof noDateRqrd == 'undefined') {
//get the current time
var Now=new Date();
dateField.value=Now.getMonth()+1 + "/" + Now.getDate() + "/" + Now.getFullYear();
} else {
dateField.value="";
}
}
return false;
} else
return true;
} //function IsDateValid
i have this way of getting tomorrows date.
var tomorrow = date.getDate() + "/" + month + "/" + date.getFullYear();
this returns 2/10/2013 where as i want it to be 02/10/2013 (with the zero for single digits)
This is needed to do a date comparison.
if(02/10/2013==2/10/2013){
dosomething();
}
The above doesnt work due to that issue.
You can do by
var tomorrow = ('0' + date.getDate()).slice(-2) + "/" + ('0' + (date.getMonth()+1)).slice(-2) + "/" + date.getFullYear();
why you don't use str_pad from phpjs.org this is the code :
function str_pad (input, pad_length, pad_string, pad_type) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + namespaced by: Michael White (http://getsprink.com)
// + input by: Marco van Oort
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
// * returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
// * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
// * returns 2: '------Kevin van Zonneveld-----'
var half = '',
pad_to_go;
var str_pad_repeater = function (s, len) {
var collect = '',
i;
while (collect.length < len) {
collect += s;
}
collect = collect.substr(0, len);
return collect;
};
input += '';
pad_string = pad_string !== undefined ? pad_string : ' ';
if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
pad_type = 'STR_PAD_RIGHT';
}
if ((pad_to_go = pad_length - input.length) > 0) {
if (pad_type === 'STR_PAD_LEFT') {
input = str_pad_repeater(pad_string, pad_to_go) + input;
} else if (pad_type === 'STR_PAD_RIGHT') {
input = input + str_pad_repeater(pad_string, pad_to_go);
} else if (pad_type === 'STR_PAD_BOTH') {
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
input = half + input + half;
input = input.substr(0, pad_length);
}
}
return input;
}
and apply it to your code:
var tomorrow = str_pad(date.getDate(),2,0,'STR_PAD_LEFT') + "/" + str_pad(month,2,0,'STR_PAD_LEFT') + "/" + date.getFullYear();
Try this:
if(new Date(2013,2,10).toString() == new Date(2013,02,10).toString()){
dosomething();
}
$.datepicker.formatDate('dd/mm/yy', tomorrow);
You could also use moment.js library for time/date manipulation