I am using JQuery to block some dates but next month are available.
A user can click on today day + 5 and all the other should be disabled.
What I am doing wrong?
<div id='datepicker' onchange="test(this)">
</div>
$('#datepicker').datepicker(
{
numberOfMonths: 2,
beforeShowDay: function (date) {
var hilight = [true, 'isActive'];
var today = new Date();
var blockdays = new Date();
// var startdayofmonth = new Date(today.getFullYear(), today.getMonth(), 1);
today.setDate(today.getDate() + 5);
blockdays.setDate(blockdays.getDate() + 12);
blockdays = moment(blockdays.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
var blockendofmonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);;
blockendofmonth = moment(blockendofmonth.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
today = moment(today.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
date = moment(date.toLocaleDateString(), 'MM.DD.YYYY').format('YYYY-DD-MM');
if (date < today) {
hilight = [false, ''];
}
else if (date >= blockdays) {
hilight = [false, ''];
}
return hilight;
}
}
);
Comparing dates string in YYYY-DD-MM format gives incorrect results. '2021-10-04' < '2021-20-03' this evaluated to true' which is actually not correct. When comparing date strings, it is better to follow YYYY-MM-DD:HH:MM:SS format for better result. Checkout below snippet.
$(document).ready(function () {
var allowDays = getAllowDays();
$('#datepicker').datepicker({
numberOfMonths: 2,
beforeShowDay: function (date) {
var hilight = [true, 'isActive'];
var start = allowDays[0];
var end = allowDays[1];
var currentDate = +moment(date).format('YYYYMMDD');
if (currentDate < start) {
hilight = [false, ''];
} else if (currentDate >= end) {
hilight = [false, ''];
}
return hilight;
}
});
});
function getAllowDays() {
var today = new Date();
var blockdays = new Date();
today.setDate(today.getDate() + 5);
blockdays.setDate(blockdays.getDate() + 12);
return [+moment(today).format('YYYYMMDD'), +moment(blockdays).format('YYYYMMDD')];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"/>
<div id='datepicker'></div>
Related
I have three <input> elements in my form.
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total" class="form-control" placeholder="Total no. of days">
out of which first and second accepts a date chosen from Bootstrap Datepicker and the last one displays total number of days.
The total number of days is calculated excluding weekends( Saturdays and Sundays). I now want to achieve a functionality as in, when I disable a set of dates using datesDisabled option, those disabled dates should not be counted to form total no. of days. How to check whether a date is disabled in Bootstrap Datepicker ?
Here is a quick JS Fiddle to my code.
Below is my JS.
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var end = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: today,
daysOfWeekDisabled: [0,6],
datesDisabled:["12-04-2018","17-04-2018","19-04-2018"],
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
daysOfWeekDisabled: [0,6],
datesDisabled:["12-04-2018","17-04-2018","19-04-2018"],
startDate: $('#from-date').val()
}).on('changeDate', function(ev) {
var fromDate = $('#from-date').data('datepicker').dates[0];
var get_no_of_days = getWorkingDatesCount(fromDate, ev.date);
var final_count = parseInt(get_no_of_days) + 1;//adding +1 to the total number of days to count the present date as well.
$('#total').val(final_count);
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
});
function getWorkingDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if ( !((dayOfWeek == 6) || (dayOfWeek == 0)) )
count++;
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
If anyone could help me with this, it'll be of great help.
Working example: https://jsfiddle.net/cCrul/qLt6k0yv/
I just declared datesDisables as a variable:
var datesDisabled = ["12-04-2018", "17-04-2018", "19-04-2018"];
and I use it to check if curDate is in that array before executing count++:
if (
!((dayOfWeek == 6) || (dayOfWeek == 0)) &&
(datesDisabled.indexOf(formatDate(curDate)) == -1)
) {
count++;
}
formatDate() function defined in the jsfiddle code.
$(function() {
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var end = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var datesDisabled = ["12-04-2018", "17-04-2018", "19-04-2018"];
// create the from date
$('#from-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
startDate: today,
daysOfWeekDisabled: [0, 6],
datesDisabled: datesDisabled,
}).on('changeDate', function(ev) {
ConfigureToDate();
});
$('#to-date').datepicker({
autoclose: true,
format: 'dd-mm-yyyy',
daysOfWeekDisabled: [0, 6],
datesDisabled: datesDisabled,
startDate: $('#from-date').val()
}).on('changeDate', function(ev) {
var fromDate = $('#from-date').data('datepicker').dates[0];
var get_no_of_days = getWorkingDatesCount(fromDate, ev.date);
var final_count = parseInt(get_no_of_days) + 1; //adding +1 to the total number of days to count the present date as well.
$('#total').val(final_count);
});
// Set the min date on page load
ConfigureToDate();
// Resets the min date of the return date
function ConfigureToDate() {
$('#to-date').val("").datepicker("update");
$('#to-date').datepicker('setStartDate', $('#from-date').val());
}
function getWorkingDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if (!((dayOfWeek == 6) || (dayOfWeek == 0)) && (datesDisabled.indexOf(formatDate(curDate)) == -1)) {
console.log(formatDate(curDate));
count++;
}
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day, month, year].join('-');
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script>
<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total" class="form-control" placeholder="Total no. of days">
i have this code for working with dates.
<script language="javascript" type="text/javascript">
$("#Reports_SignUpDateAfter_container").datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'dd-mm-yy', //"dd-mm-yy",
gotoCurrent: true,
yearRange: '-10:+10',
onSelect: function() {
Reports_SignUpDateAfter_changeDate(false);
}
});
// react on manual text box editing
$("#Reports_SignUpDateAfter_container").change(function() {
Reports_SignUpDateAfter_changeDate(true);
});
function Reports_SignUpDateAfter_changeDate(manualChange) {
var newDate = $("#Reports_SignUpDateAfter_container").datepicker("getDate");
if (newDate != null) {
// add time information
newDate = DateUtils.copyTimeFrom("#Reports_SignUpDateAfter_local", newDate);
DateUtils.setDate("#Reports_SignUpDateAfter_local", newDate);
// convert local to UTC
Reports_SignUpDateAfter_localToUTC();
if (manualChange) {
$("#Reports_SignUpDateAfter_container").datepicker("setDate", newDate)
}
} else { // empty
$("#Reports_SignUpDateAfter_local").val("");
$("#Reports_SignUpDateAfter").val("");
}
}
// new date as UTC
function Reports_SignUpDateAfter_setDate(newDate) {
// store time into hidden inputs
DateUtils.setDate("#Reports_SignUpDateAfter", newDate);
// set local drop downs and hidden input
var dateString = DateUtils.getString(newDate);
dateString = DateUtils.fromUTCToLocal(dateString);
var localDate = DateUtils.getDateFromString(dateString);
DateUtils.setDate("#Reports_SignUpDateAfter_local", localDate);
$("#Reports_SignUpDateAfter_container").datepicker("setDate", localDate);
};
function Reports_SignUpDateAfter_localToUTC() {
// get string and convert to UTC
var dateString = $("#Reports_SignUpDateAfter_local").val();
dateString = DateUtils.fromLocalToUTC(dateString);
$("#Reports_SignUpDateAfter").val(dateString);
// conversion end
}
;
</script>
Problem is when i chose Start and End date like 2015-11-02 and end date 2015-11-04 it always convert me the date to UTC(-1:00h) but it doesn't consider the winter and summer date changes. For that date is should be the same(UTC and local). Is there any clue why is that so ?
var DateUtils = DateUtils || {
getDate: function (selector) {
var value = $(selector).val();
if (value == null || value == "") {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date = DateUtils.cleanSeconds(date);
return date;
}
return DateUtils.getDateFromString(value);
},
getClientTimeDifferenceFromUTC: function () {
var d = new Date()
return d.getTimezoneOffset();
},
setDate: function (selector, date) {
if (date != null) {
var old = DateUtils.getDate(selector);
old.setTime(date.getTime());
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
} else {
$(selector).val("");
}
},
// copies time from selector and date part from date
copyTimeFrom: function (selector, date) {
var value = $(selector).val();
if (date != null && value != null && value != "") {
var old = DateUtils.getDate(selector);
date.setHours(old.getHours());
date.setMinutes(old.getMinutes());
}
return date;
},
setHour: function (selector, hour) {
var old = DateUtils.getDate(selector);
old.setHours(hour);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
setMinute: function (selector, minute) {
var old = DateUtils.getDate(selector);
old.setMinutes(minute);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
cleanSeconds: function (date) {
date.setSeconds(0);
date.setMilliseconds(0);
return date;
},
// formats date into yyyy-mm-dd hh:mm format
getString: function (date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
hours = ('0' + hours).slice(-2);
minutes = ('0' + minutes).slice(-2);
return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
},
// formats string from yyyy-mm-dd hh:mm into date
getDateFromString: function (date) {
if (date == undefined || date == null) {
return null;
}
var m = date.match(/Date\((\d+)\)/); //handle .NET MVC Date format (i.e. "/Date(1426598616621)/")
if (m) {
return new Date(parseInt(m[1]));
}
var year = date.substring(0, 4);
var month = date.substring(5, 7);
var day = date.substring(8, 10);
var hours = date.substring(11, 13);
var minutes = date.substring(14, 16);
var newDate = new Date(year, month - 1, day, hours, minutes);
// newDate.setYear(year);
// newDate.setDate(1);
// newDate.setMonth(month - 1);
// newDate.setDate(day);
// newDate.setHours(hours);
// newDate.setMinutes(minutes);
newDate = DateUtils.cleanSeconds(newDate);
return newDate;
},
// dateString in format yyyy-mm-dd hh:mm
fromLocalToUTC: function (dateString) {
var date = this.fromLocalToUTCDate(dateString);
return this.getString(date);
},
fromLocalToUTCDate: function (dateString) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from local date/time to UTC
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() + offSet;
d.setTime(millis);
// *****
return d;
},
// dateString in format yyyy-mm-dd hh:mm
// returns date as string
fromUTCToLocal: function (dateString) {
var date = this.fromUTCToLocalDate(dateString);
return this.getString(date);
},
// dateString in format yyyy-mm-dd hh:mm
// returns date object
fromUTCToLocalDate: function (dateString, setOffset) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from UTC to local date/time
if (setOffset != false) {
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() - offSet;
d.setTime(millis);
}
// *****
return d;
},
When I inputted the code below into jsfiddle it worked exactly as I wanted. However when I implemented it into my project the value returns as NaN.
<script type="text/javascript">
$(function () {
$('#datepicker8').datepicker({
showOnFocus: false,
showTrigger: '#calImg',
beforeShowDay: $.datepicker.noWeekends,
pickerClass: 'noPrevNext',
dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true,
onSelect: function (dateStr) {
var min = $(this).datepicker('getDate');
$('#datepicker9').datepicker('option', 'minDate', min || '0');
datepicked();
}
});
$('#datepicker9').datepicker({
showOnFocus: false,
showTrigger: '#calImg',
beforeShowDay: $.datepicker.noWeekends,
pickerClass: 'noPrevNext',
dateFormat: "dd-mm-yy", changeMonth: true, changeYear: true,
onSelect: function (dateStr) {
var max = $(this).datepicker('getDate');
$('#datepicker8').datepicker('option', 'maxDate', max || '+1Y');
datepicked();
}
});
});
var datepicked = function () {
var from = $('#datepicker8');
var to = $('#datepicker9');
var nights = $('#CalcDate1');
var startDate = from.datepicker('getDate');
startDate.setDate(startDate.getDate() + 1);
var endDate = to.datepicker('getDate')
// Validate input
if (endDate && startDate) {
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - (startDate + 1); // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
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 (startDay - endDay > 1)
var days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
var days = days - 1
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
var days = days - 1
nights.val(days);
}
}
</script>
I added the code below thinking that it would deal with NaN but it hasn't worked.
if (!isNaN(days)) {
document.getElementById('CalcDate1').value = days;
}
else {
document.getElementById('CalcDate1').value = "";
}
The jsfiddle link is JsFiddle
Its this line here:
var diff = endDate - (startDate + 1);
that is causing the issue. On your fiddle where its working
var diff = endDate - startDate;
This is causing the issue because endDate and startDate are objects and you are trying to concatenate an object with a number
I have two JQuery datepicker on my page, I want to put all the days between the two dates to an array.
How Can I work it out?
Here is my snippet:
function mennyi() {
var dtFrom = document.getElementById('arrival').value;
var dtTo = document.getElementById('departure').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getDate() - dt1.getDate();
var days = diff;
alert(dtTo);
document.getElementById("nights").innerHTML = days + " nights"; {
$('#arrival').datepicker({ dateFormat: 'dd-mm-yy' }).val();
$('#departure').datepicker({ dateFormat: 'dd-mm-yy' }).val();
var start = new Date(document.getElementById('arrival').value),
end = new Date(document.getElementById('departure').value),
currentDate = new Date(start),
between = []
;
while (end > currentDate) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
$('#lista').html(between.join('<br> '));};
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
};
Now it works, but the thing is how can I change the date format, before I put the string into the array?
Good day,
I'm having a little trouble with calculating number of days from now to a selected date after selecting a date from jQuery datepicker.
I think that the datepicker is changing the date formatting of the date on selection and causing the calculation to go wrong but I can't quite figure out how to counter this. I am sure it is me but I can't see the forest for the trees so any suggestions would be really helpful.
Here is the code:
<input type="text" class="datepicker-calc" />
<input type="text" id="tbAddDays" />
$(document).ready(function () {
$(".datepicker-calc").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date, e) {
var expDate = new Date(date);
var date = e.selectedDay;
if (date < 10) {
date = ("0" + e.selectedDay)
}
var month = e.selectedMonth;
if (month < 10) {
month = ("0" + e.selectedMonth)
}
var year = e.selectedYear;
var endDate = month + "/" + date + "/" + year;
updateDays(endDate, e);
$(".datepicker-calc").datepicker("hide");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var exp = new Date(expDate);
var endDate = exp.toDateString('dd/MM/yyyy');
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
$('#tbAddDays').val(totalDays);
}
});
The onSelect event will receive a string in the specified format, which is dd/mm/yy. JavaScript Date.parse method will parse such dates incorrectly, or not parse them at all. The solution is to use parseDate() function built into jQuery ui:
onSelect: function (dateText, inst) {
var expDate = $.datepicker.parseDate(inst.settings.dateFormat, dateText, inst.settings);
var diff = expDate - new Date();
var days = diff / 1000 / 60 / 60 / 24;
alert( /* ceil, floor, round */ days);
}
Realised that I need the display to be in jQuery dd/mm/yy (dd/mm/yyyy) format so kept that and did some manipulation to the expDate being passed to the updateDays() method to ensure that the date to be calculated would be handled correctly by JS.
Working script:
$(".datepicker-calc").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
onSelect: function (selectdate, e) {
var newDate = selectdate.slice(0,2);
var newMonth = selectdate.slice(4,6);
if (newMonth < "10") { newMonth = ("0" + newMonth.slice(0,1));};
var newYear = selectdate.slice(6,11);
var expDate = newMonth + "/" + newDate + "/" + newYear;
updateDays(expDate, e);
$(".datepicker-calc").datepicker("hide");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var expire = new Date(expDate);
var endDate = expire.toDateString('dd/MM/yyyy');
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
$('#tbAddDays').val(totalDays);
}