Please check this JSFIDDLE and help me to solve below issue. I am really stuck on this.
If I select first calendar value is 19(tuesday). I need result like 20,21,22,23 with back shade(light color).
In below code If nights = 4 and arrival = 2 the result showing in calendar is correct. But, If nights = 4 and arrival = 6 the result showing in calendar is wrong. please check attached images.
// hotel nights.. available is 2, 3, 4, 5, 6, 7, 8, 9 nights.
var nights = 4;
// arrival weekday in hotel: monday = 1, tuesday = 2, wednesday = 3, thursday = 4, friday = 5, saturday =6, sunday = 7
var arrival = 2;
nights = 4 and arrival = 2
nights = 4 and arrival = 6
Finally issue solved. Click Here
Updated script
function initializeBooking() {
$('#form_booking').ajaxSubmit({
target: '#result',
success: function () {
$('#result').fadeIn('slow');
}
});
return false;
}
// hotel nights.. available is 2, 3, 4, 5, 6, 7, 8, 9 nights.
var nights = 2;
// arrival weekday in hotel: monday = 1 ..... sunday = 7
var arrival = 7;
// flexbooking = no .. otherwise you can arrive when you want.
var flex_booking = 'no';
var couter = arrival + nights;
var diff = 0;
if(couter>7)
diff = couter-7;
$(function () {
cal_start = new Date();
cal_start.setTime(cal_start.getTime() + (24 * 60 * 60 * 1000 * 1));
$("#datepicker_begin").datepicker({
showWeek: true,
beforeShowDay: function (date) {
weekday = date.getDay();
if (weekday == 0)
weekday = 7;
if (flex_booking == 'no') {
if (weekday == arrival) {
result = [true, "relevant"]; // clickable for the arrival day
} else if (weekday > arrival && weekday <= (arrival + nights)) {
result = [false, "relevant"]; // red but no clickable for the days you are staying in the hotel
} else {
result = [false, ""]; // normal days outside the booking range. could be possible nights > 6 that this is not set and everything is red
}
if(diff>0 && weekday<=diff)
{
result = [false, "relevant"];
}
} else {
result = [true, "relevant"];
}
return result;
},
altField: "#date_begin",
altFormat: "#",
showOtherMonths: false,
selectOtherMonths: false,
numberOfMonths: 3,
dateFormat: "dd.mm.yy",
firstDay: 1,
minDate: cal_start,
maxDate: "+12m",
onSelect: function () {
begin = eval($("#date_begin").val());
start = new Date();
start.setTime(begin);
days = nights;
end = new Date();
end.setTime(begin + (24 * 60 * 60 * 1000 * days));
$("#date_end").val(begin + (24 * 60 * 60 * 1000 * days));
after = new Date();
after.setTime(begin + (24 * 60 * 60 * 1000 * days) + (24 * 60 * 60 * 1000));
$("#datepicker_end").val(('0' + end.getDate()).slice(-2) + '.' + ('0' + (end.getMonth() + 1)).slice(-2) + '.' + end.getFullYear());
$("#nights_span").html(new Date(end - begin) / 1000 / 60 / 60 / 24);
$("#datepicker_end").datepicker("destroy");
$("#datepicker_end").datepicker({
beforeShowDay: function (date) {
return [false, ""];
},
altField: "#date_end",
altFormat: "#",
minDate: new Date(end),
maxDate: new Date(after),
showOtherMonths: false,
selectOtherMonths: false,
numberOfMonths: 1,
dateFormat: "dd.mm.yy",
firstDay: 1,
onSelect: function (dateText) {
initializeBooking();
}
});
initializeBooking();
}
});
});
Related
I am stuck in between with my problem of "How to calculate the days between the dates excluding the Weekends(SAT,SUN) and the National Holidays." and really struggling to calculate the weekends and nationaldays holidays both as the same time.
Any Help would be severely appreciated.
I have arrived to the conclusion in my code , that i am getting the calculated days where i am able to exclude the weekends , but not the national holidays, I have tried to built but failed. Please let me know how to calculate both the weekends and national holidays simultaneously.
This is my html code:
<label>Leave From</label>
<input name="from" id="from" type="text" class="form-control" value="" / >
</div>
<div class="form-group" id="to_date">
<label>To</label>
<input name="to" id="to" type="text" class="form-control" >
</div>
<input type="text" id="hasil" name="hasil" readonly />
This is my script:
<script>
var disabledDays = ["3-24-2015", "3-25-2015"];
function nationalDays(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 || new Date() > date) {
return [false];
}
}
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
$(function () {
$("#from").datepicker({
minDate:0,
changeMonth: true,
constrainInput: true,
numberOfMonths: 1,
beforeShowDay: $.datepicker.noWeekends,
onSelect: calculateDays,
onClose: function (selectedDate) {
var day = $("#from").datepicker('getDate');
$("#to").datepicker("option", "minDate", selectedDate);
},
}).on("changeDate",function(ev){
var fromdate = new Date(ev.date);
fromdate.setMonth(fromdate.getMonth()+1);
var finaldate = fromdate.getFullYear()+"-"+fromdate.getMonth()+"-"+fromdate.getDate();
console.log(finaldate);
$("#fromdate").val(finaldate);
});
});
$(function () {
$("#to").datepicker({
minDate:0,
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
constrainInput: true,
numberOfMonths: 1,
onSelect: calculateDays,
onClose: function (selectedDate) {
$("#from").datepicker("option", "maxDate", selectedDate);
},
}).on("changeDate",function(ev){
var todate = new Date(ev.date);
todate.setMonth(todate.getMonth()+1);
var finaldate = todate.getFullYear()+"-"+todate.getMonth()+"-"+todate.getDate();
console.log(finaldate);
$("#todate").val(finaldate);
});
});
function calculateDays(startDate, endDate) {
var form = this.form
var startDate = document.getElementById("from").value;
var startDate = new Date(startDate);
var endDate = document.getElementById("to").value;
var endDate = new Date(endDate);
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var oneDay = 24 * 60 * 60 * 1000;
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / oneDay);
var weeks = Math.floor(days / 7);
var days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (endDate < startDate) {
return 0;
}
if (startDay - endDay > 1) days = days - 2;
if (days) document.getElementById("hasil").innerHTML = days;
$("#hasil").val(days);
}
</script>
Here is the link to jsfiddle: https://jsfiddle.net/8ww4noja/2/
I want to calculate age when date is selected by using jquery date picker. I added code below but it showing minus value if i select date like '19/03/2015','15/01/2015' or '19/03/2014' ,'31/12/2014'
$(document).ready(function ()
{
console.log($(document).width());
$('#patientDob').datepicker
({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1900:2150',
maxDate: new Date(),
inline: true,
onSelect: function() {
var birthDay = document.getElementById("patientDob").value;
var DOB = new Date(birthDay);
var today = new Date();
var age = today.getTime() - DOB.getTime();
age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
document.getElementById('patientAge').value = age;
}
});
});
I have created this age calculator for my project
using jQuery UI. and JavaScript function. you will get the exact result.
It it will calculate age and display as human readable.
create a date field with ID 'datepicker'and import jquery and jquery ui . After that
Then just copy and paste the code to get the exact result.
output // 28 years 7 months 7 days
$(function () {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
showAnim: 'slideDown',
dateFormat: 'yy-mm-dd'
}).on('change', function () {
var age = getAge(this);
/* $('#age').val(age);*/
console.log(age);
alert(age);
});
function getAge(dateVal) {
var
birthday = new Date(dateVal.value),
today = new Date(),
ageInMilliseconds = new Date(today - birthday),
years = ageInMilliseconds / (24 * 60 * 60 * 1000 * 365.25 ),
months = 12 * (years % 1),
days = Math.floor(30 * (months % 1));
return Math.floor(years) + ' years ' + Math.floor(months) + ' months ' + days + ' days';
}
});
AFAIK The javascript Date requires yyyy/mm/dd, and you are sending:
var DOB = new Date(birthDay); // dateFormat: 'dd/mm/yy'
Change format to "yyyy/mm/dd" and will work ok.
I'm using the code from JQuery UI Datepicker Disbale Next Day After 12pm to disable weekends, public holidays and next day (if selected after 10am), but I'm stuck on how to only allow Tuesday, Wednesday and Thursday to be selected.
// dates
var dateMin = new Date();
var weekDays = AddWeekDays(1);
dateMin.setDate(dateMin.getDate() + weekDays);
var natDays = [
[1, 1, 'uk'],
[12, 25, 'uk'],
[12, 26, 'uk']
];
function noWeekendsOrHolidays(date) {
var noWeekend = $j.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
function AddWeekDays(weekDaysToAdd) {
var mydate = new Date();
if (mydate.getHours()>=10)
var daysToAdd = 1;
else var daysToAdd = 0;
var day = mydate.getDay()
weekDaysToAdd = weekDaysToAdd - (5 - day)
if ((5 - day) < weekDaysToAdd || weekDaysToAdd == 1) {
daysToAdd = (5 - day) + 2 + daysToAdd
} else { // (5-day) >= weekDaysToAdd
daysToAdd = (5 - day) + daysToAdd
}
while (weekDaysToAdd != 0) {
var week = weekDaysToAdd - 5
if (week > 0) {
daysToAdd = 7 + daysToAdd
weekDaysToAdd = weekDaysToAdd - 5
} else { // week < 0
daysToAdd = (5 + week) + daysToAdd
weekDaysToAdd = weekDaysToAdd - (5 + week)
}
}
return daysToAdd;
}
$j('.input-text.addon.addon-custom').datepicker({
beforeShowDay: noWeekendsOrHolidays,
minDate : dateMin,
defaultDate: +1,
firstDay: 1,
changeFirstDay: true,
dateFormat: "DD, dd MM yy"
});
Any help would be very much appreciated.
Fiddle here: http://jsfiddle.net/prydonian/4k4gga6j/
On your datepicker function, add the "beforeShowDay" option like this.
jQuery('#datepicker').datepicker({
minDate: dateMin,
defaultDate: +1,
firstDay: 1,
changeFirstDay: true,
dateFormat: "DD, dd MM yy",
beforeShowDay: function(day){
if (day.getDay()<2 || day.getDay()>4){
return [false, ""];
}
return noWeekendsOrHolidays(day);
}
});
here is the Fiddle updated: http://jsfiddle.net/4k4gga6j/3/
If I understood you right, you need to exclude any day other than Tuesday, Wednesday and Thursday? If the answer is yes, then you should add the following code to your existing noWeekendsOrHolidays method:
($.inArray(date.getDay(), [2, 3, 4]) != -1)
here is updated jsFiddle http://jsfiddle.net/4k4gga6j/4/
I am working on a site for a client, on the site I use the Jquery UI Calendar, I need to be able to highlight 3 business days starting 2 days after the current date but incorporate math to not count the weekends. Here is my fiddle:
JS Fiddle
Here is the HTML
<input type="text" id='datepicker'>
Here is the JS
var SelectedDates = {};
SelectedDates[new Date('04/14/2014')] = new Date('04/14/2014');
SelectedDates[new Date('04/15/2014')] = new Date('04/15/2014');
SelectedDates[new Date('04/16/2014')] = new Date('04/16/2014');
$('#datepicker').datepicker({
minDate: 2,
maxDate: "+4M +15D",
beforeShowDay: function (date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true, "Highlighted", Highlight];
} else {
return [true, '', ''];
}
}
});
I am having trouble adding beforeShowDay: $.datepicker.noWeekends to the code above. I also need the 3 dates that are highlighted to be variable so they change depending on what the current date is but I am still learning JS and I don't understand the logic behind that.
I have looked all over this site and others and although there are a lot of questions/answers on how to highlight specific dates, none fully apply to what I am trying to do.
So just to clarify I need to do math to figure out how to negate the minDate and weekends and highlight the next three business days.
This should do it:
jsFiddle example
$(document).ready(function () {
var css, count = 0,
gap = 0,
today = new Date();
$('#datepicker').datepicker({
showOtherMonths: true,
selectOtherMonths: true,
minDate: 2,
maxDate: "+4M +15D",
beforeShowDay: function (date) {
var day = date.getDay();
var diff = new Date(date - today);
var numDays = Math.ceil(diff / 1000 / 60 / 60 / 24);
if (numDays > 0 && count < 3) {
if (day != 6 && day != 0) {
gap++;
if (gap > 1) {
count++;
css = 'Highlighted';
} else css = '';
}
} else css = '';
return [(day != 6) && (day != 0), css]; //0-Sunday 6-Saturday
},
onSelect: function () {
count = 0;
gap = 0;
}
});
});
UPDATE
Here is one way to do it:
var currentDay = new Date();
var dayOfWeek;
var highlighted = 0;
var count = 0;
var SelectedDates = {};
while(highlighted < 3){
dayOfWeek = currentDay.getDay();
if(dayOfWeek != 0 && dayOfWeek != 6){
if(count > 1){
alert(currentDay);
var month = currentDay.getMonth()+1;
if(month.toString().length < 2)
month = '0'+month;
var day = currentDay.getDate();
if(day.toString().length < 2)
day = '0'+day;
var year = currentDay.getFullYear();
var dateStr = month+"/"+day+"/"+year;
SelectedDates[new Date(dateStr)] = new Date(dateStr);
highlighted++;
}
else {
count++;
}
}
currentDay = new Date(currentDay.getTime() + (24 * 60 * 60 * 1000));
}
Example:
FIDDLE
I have 2 inputs where dates are selected #startdate and #enddate. I am using datepicker and have currently disabled weekends and holidays, this is working great!
I then have a #days input which calculates the difference between the 2 dates, this date difference then has a weekend count taken from it.
I would like to create a holiday count so I can also minus this from the differnce in days.
So i would end up with
$('#days').val((Math.abs(($d2new-$d1new)/86400000) - weekend_count - holidaycount) + 1);
My current code is as follows (this has been taken form other stackoverflow questions and is working great :) towards the bottom is the var holidaycount which is what i am struggling with. Any help would be greatly appreciated.
//holidays
var natDays = [
[1, 1, 'uk'],
[1, 2, 'uk'],
[1, 3, 'uk'],
[1, 4, 'uk'],
[12, 24, 'uk'],
[12, 25, 'uk'],
[12, 26, 'uk'],
[12, 27, 'uk'],
[12, 28, 'uk'],
[12, 29, 'uk'],
[12, 30, 'uk'],
[12, 31, 'uk']
];
function noWeekendsOrHolidays(date) {
var noWeekend = $.datepicker.noWeekends(date);
if (noWeekend[0]) {
return nationalDays(date);
} else {
return noWeekend;
}
}
function nationalDays(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {
return [false, natDays[i][2] + '_day'];
}
}
return [true, ''];
}
// do initialization here
$("#startdate").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
yearRange: '0:+100',
beforeShowDay: noWeekendsOrHolidays,
onSelect: function( selectedDate ) {
$("#enddate").datepicker("option","minDate",selectedDate );
$("#enddate2").datepicker("option","minDate",selectedDate );
},
minDate: '+1d',
maxDate: '+' + DAY_DIFFERENCE + 'd'
});
// do initialization here
$("#enddate").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
yearRange: '0:+100',
beforeShowDay: noWeekendsOrHolidays,
maxDate: '+' + DAY_DIFFERENCE + 'd'
});
// do initialization here
$("#enddate2").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
yearRange: '0:+100',
beforeShowDay: noWeekendsOrHolidays,
onSelect: function( selectedDate ) {
$d1 = $('#startdate').val();
$d2 = $('#enddate2').val();
$myDateParts1 = $d1.split("-");
$myDateParts2 = $d2.split("-");
$d1flip = new Date($myDateParts1[2], ($myDateParts1[1]-1), $myDateParts1[0]);
$d2flip = new Date($myDateParts2[2], ($myDateParts2[1]-1), $myDateParts2[0]);
$newdate1 = $d1flip.format("ddd mmm dd hh:MM:ss yyyy");
$newdate2 = $d2flip.format("ddd mmm dd hh:MM:ss yyyy");
// For Opera and older winXP IE n such
$d1new = Date.parse($newdate1);
$d2new = Date.parse($newdate2);
var weekend_count = 0;
for (i = $d1new.valueOf(); i <= $d2new.valueOf(); i+= 86400000){
var temp = new Date(i);
if (temp.getDay() == 0 || temp.getDay() == 6) {
weekend_count++;
}
}
var holidaycount = 0;
for (i = $d1new.valueOf(); i <= $d2new.valueOf(); i+= 86400000){
var temp = new Date(i);
if (**date in var natDays & is in selected difference range**) {
holidaycount++;
}
}
console.log(weekend_count);
console.log(holidaycount);
$('#days').val((Math.abs(($d2new-$d1new)/86400000) - weekend_count - holidaycount) + 1);
}
});
}, 'html');
return false;
});
}
EDIT
From the answer, I have inserted the function and tried this....
console.log(holidaycount); returns 0 but with the chosen dates i selected it should have been 10
var holidaycount = 0;
for (i = $d1new.valueOf(); i <= $d2new.valueOf(); i+= 86400000){
var temp = new Date(i);
if (isHoliday(temp)) {
holidaycount++;
}
}
UPDATE: modified getMonth() to getMonth() + 1 accordingly to the comments.
**date in var natDays & is in selected difference range**
date is in selected difference range is always true as new Date(i) is inside said range (just like in the loop for weekend_count: you didn't bother with checking whether you're in the range).
Now, checking if the date inside temp is a holiday, you may want to use a function (though you still can do it straight in your code):
/* dateObject is a JS Date object (e.g. dateObject = new Date();) */
/* country is the country we test holidays for */
function isHoliday(dateObject, country) {
/* let's assume natDays is global, otherwise pass it as a third argument to this function */
for(var i = 0; i < natDays.length; i++) {
/* natDays[i][0] is a day, natDays[i][1] is a month, natDays[i][2] is a country indicator */
if(parseInt(dateObject.getDate()) == parseInt(natDays[i][0]) && parseInt(dateObject.getMonth()) + 1 == parseInt(natDays[i][1]) && country.toLowerCase() == natDays[i][2].toLowerCase()) {
/* found a day and a month matching our current Date's day and month: interrupt and tell caller dateObject is a holiday */
return true;
}
}
/* end of loop, we parsed all possible holidays without finding any match for our Date: tell caller the given Date is not a holiday */
return false;
}
Now to put it in your code:
if (isHoliday(temp, 'uk')) {
holidaycount++;
}
This should do the trick, though it may require some refactoring (did not test this code), and there is probably more elegant ways to do it (like modding the Date object's prototype to use this function as a method of the object).