Javascript set date for next 2 days - javascript

I am using bootstrap datepicker and my code is:
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#start_date').datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
checkin.hide();
}).data('datepicker');
var checkin1 = $('#end_date').datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
checkin1.hide();
}).data('datepicker');
Its start from today date.
Now I want to start from tomorrow after day or set next 5 days. How to solve this?

var addDays = new Date();
addDays.setDate(addDays.getDate() + 6); //add six days
Then set this date to your datepicker
$("#start_date").datepicker("setDate", addDays);
It is not enough to set only the date, inorder to update the UI add the below code
$("#start_date").datepicker('update');
Do all these after initialising the bootstrap datepicker.

try this:
var date = new Date(); // now
date.setDate( date.getDate() + 6); //Add six days
And then use it on your date picker.

Related

6Jquery datepicker date blocking not working?

I have written code to block past dates and dates in the unavilabledates array, but only the second element of the array is blocked, rest are available for selection. Any idea how to figure it out?
var unavailableDates = ["6-3-2016", "5-28-2016", "5-27-2016", "6-28-2016"];
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender:function(date){
dmy = (date.getMonth() + 1) + "-" +date.getDate() + "-" + date.getFullYear();
return (date.valueOf() < now.valueOf() || ($.inArray(dmy, unavailableDates) == 1))?'disabled':'';
}
}
Output:// 5-28-2016 blocked , rest are not
I presume you use the jQuery UI Datepicker, use the beforeShowDay function instead of the onRender:
var unavailableDates = ["2016-03-06"]; // Dates formatted the same way as the beforeShowDay formatDate() function requires it
$('#dpd1').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ unavailableDates.indexOf(string) == -1 ]
},
minDate: 0
});
EDIT
I found the error, the formatDate('yy-mm-dd') in the beforeShowDay function checks for a 2016-05-25 date, while your provided array has dates like 6-3-2016. This is way the dates are not disabled.
See the updated code and a jsfiddle to go with it: https://jsfiddle.net/orttL83d/ (In this example I disabled 26th of May and all past dates)

Jquery datepicker reducing one day from selected epoch time

I have two Jquery datepickers namely "startDate" and "endDate". I initialize them like this.
$(function() {
$("#startdate").datepicker({ dateFormat: 'yy-mm-dd' });
$("#enddate").datepicker({ dateFormat: 'yy-mm-dd' });
});
Now i convert this date to epoch by doing this.
var sDate = startdate.split('-');
var eDate = enddate.split('-');
var sepoch = new Date(sDate[0], sDate[1] - 1, sDate[2]).getTime() / 1000;
var eepoch = new Date(eDate[0], eDate[1] - 1, eDate[2]).getTime() / 1000;
startdate = sepoch.toString();
enddate = eepoch.toString();
Now when i check the dates after converting them back from epoch, they differ by one day. So one day has been reduced from them. I can't figure out where i am going wrong. Please help me out here.
Please have a look at the fiddle, I have added a bit of code and I am getting the date that I chose from the datepicker
FIDDLE
$("#startdate").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(date) {
DoStuff();
}
});
function DoStuff() {
var startdate = $("#startdate").val();
var sDate = startdate.split('-');
var sepoch = new Date(sDate[0], sDate[1] - 1, sDate[2]).getTime() / 1000;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(sepoch);
console.log(sDate[2]);
console.log(d);
}

How to set Min and Max Date in Jquery Date Selection depending on current date

The JSFiddle Can be Found Here: http://jsfiddle.net/PQfDc/682/
I need it to:
Pick a date in a 365 day period based on user selection input. For example is a user inputs 01/01/2016, they can only select a date between 01/01/2016 and 01/01/2017 and nothing after that.
I have also set a method where if the date is before 31st Jan the minimum the start and end date can vary. For example the only dates a user can choose from are 31/01/2015 - 31/12/2016
var d = new Date(); var Month = d.getMonth();var Month = Month + 1;
var Year = d.getFullYear(); var Day = d.getDate();
if(Day <= 9){ var Day = "0".concat(Day);}
if(Month <= 9){ var Month = "0".concat(Month);}
if(Month == 01 && Day <= 31){
var Year = Year - 1;
var MinYear = "31-01-"+Year;
var Year = Year + 1;
var MaxYear = "31-12-"+Year;
} else {
var MinYear = "31-01-"+Year;
var Year = Year + 1;
var MaxYear = "31-12-"+Year;
}
$(function() {
/* global setting */
var datepickersOpt = {
dateFormat: 'dd-mm-yy',
minDate : 0
}
$("#TxtStrtDate").datepicker($.extend({
onSelect: function() {
var minDate = $(this).datepicker('getDate');
minDate.setDate(minDate.getDate()-365); //add two days
$("#TxtExpDte").datepicker( "option", "minDate", minDate);
}
},datepickersOpt));
$("#TxtExpDte").datepicker($.extend({
onSelect: function() {
var maxDate = $(this).datepicker('getDate');
maxDate.setDate(maxDate.getDate()+365);
$("#TxtStrtDate").datepicker( "option", "maxDate", maxDate);
}
},datepickersOpt));
});
Based on your JSFiddle example:
var datepickersOpt = {
dateFormat: 'dd-mm-yy',
minDate : 0
}
$("#TxtStrtDate").datepicker($.extend({
onSelect: function() {
var minDate = $(this).datepicker('getDate');
var maxDate = new Date();
$('#TxtExpDte').datepicker('option', 'minDate', minDate);
// add 365 days to the selected date
maxDate.setDate(minDate.getDate() + 365);
$("#TxtExpDte").datepicker( "option", "maxDate", maxDate);
}
},datepickersOpt));
$("#TxtExpDte").datepicker($.extend({},datepickersOpt));
Link to JSFiddle: http://jsfiddle.net/2op64ytL/1/
Result:

Allow 1 day booking with bootstrap-datepicker

I have been working with bootstrap-datepicker with little luck. I have the following code but wish to allow a 1 day booking (i.e. picker1 - From date 01/01/15 and picker 2 - To date 01/01/15. At the moment it only allows me to pick the next day for the To date after selecting the initial From date.
At the moment a 1 day booking is classed as 24 hours, over 2 dates (i.e. From 01/01/15 - 02/01/15) would be classed as a 1 day booking and charged at the 1 day rate.
How do I edit the code below or the Javascripts for Bootstrap-Datepicker to allow 1 day bookings to have the same to and from dates? and if the from date is the next day (i.e. 01/01/15 - 02/01/15) charge at a 2 day rate?
var hire_from = null;
var hire_to = null;
var setPrice = function () {
var oneDay = 24*60*60*1000;
if (hire_from && hire_to) {
var diffDays = Math.round(Math.abs((hire_from - hire_to)/(oneDay)));
var price = diffDays*$("#enquiry_price").val();
$("span#weekly_price").html("£ "+price.toFixed(0))
var fee = price*$("#enquiry_discount").val()
$("span#commission").html(fee.toFixed(0));
}
}
var initDatepickers = function(picker1, picker2){
if($(picker1)[0] && $(picker2)[0]){
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $(picker1).datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
},
format: 'dd/mm/yyyy'
}).on('changeDate', function(ev) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate());
checkout.setValue(newDate);
hire_from = newDate;
setPrice();
$.post('/enquiries/presave', {'hire_from': $.datepicker.formatDate('dd/mm/yy', hire_from), authenticity_token: window._token}, function(data){}, 'json');
checkin.hide();
$(picker2)[0].focus();
}).data('datepicker');
var checkout = $(picker2).datepicker({
onRender: function(date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}, format: 'dd/mm/yyyy'
}).on('changeDate', function(ev) {
checkout.hide();
var newDate = new Date(ev.date)
hire_to = newDate;
$.post('/enquiries/presave', {'hire_to': $.datepicker.formatDate('dd/mm/yy', hire_to), authenticity_token: window._token}, function(data){}, 'json');
setPrice();
}).data('datepicker');
}
};
Thank you for your input and help.
Try setting the picker2 onRender() to:
return date.valueOf() < checkin.date.valueOf() ? 'disabled' : '';
to enable the second datepicker to accept the same day.
Then use:
var diffDays = Math.ceil(Math.abs((hire_to - hire_from + 1) /(oneDay)));
to make the same day checkout be counted as a day's charge, and the next day checkout as 2 days

Disable/Enable selected date range on jQuery datepicker UI

So I have the following demo http://dev.driz.co.uk/week.html that shows a jQuery UI datepicker that has multiple instances for each month of the year.
I've modified it so that the user selects entire weeks and then start and end dates for those weeks are stored on the right hand sidebar with a week number.
What I want to do is disable the dates once the user has selected them so they can see on the calender picker what dates have been selected (and also prevent them from adding the same date range more than once).
However I don't know where to start with this... I've created some enable and disable date functions but don't know how to actually disable the dates using the beforeShowDay method.
For example:
var array = ["2013-03-14","2013-03-15","2013-03-16"]
$('.week-picker').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
}
});
But how would I disable a range of dates? As I only have the start and end dates. And can I call the beforeShowDay AFTER the datepicker is on the page like in my example? AND how can I then re-enable the dates?
Here's the code:
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active');
}, 1);
}
$('.week-picker').datepicker( {
defaultDate: '01/01/2014',
minDate: '01/01/2013',
maxDate: '01/01/2015',
changeMonth: false,
changeYear: true,
showWeek: true,
showOtherMonths: true,
selectOtherMonths: true,
numberOfMonths: 12,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
addWeek($.datepicker.iso8601Week(new Date(dateText)), $.datepicker.formatDate( dateFormat, startDate, inst.settings ), $.datepicker.formatDate( dateFormat, endDate, inst.settings ));
disableDates( $.datepicker.formatDate( dateFormat, startDate, inst.settings ), $.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
$('.remove').live('click', function(e){
enableDates($(this).attr('data-startdate'), $(this).attr('data-enddate'));
$(this).parent('div').remove();
});
});
// adds the week to the sidebar
function addWeek(weekNum, startDate, endDate){
$('.weeks-chosen').append('<div data-startdate="'+startDate+'" data-enddate="'+endDate+'"><span class="weekNum">Week '+ (weekNum - 1) +'</span> - <span class="startDate">'+startDate+'</span> - <span class="endDate">'+endDate+'</span> | <span class="remove">X Remove</span></div>');
}
// disable the dates on the calendar
function disableDates(startDate, endDate){
}
// enable the dates on the calendar
function enableDates(startDate, endDate){
}
In short there are two questions here... How do I disable dates AFTER the datepicker is added to the page. And second how do I disable a range between two dates, as it looks like the beforeShowDay method expects an array of dates rather than a range.
But how would I disable a range of dates? As I only have the start and
end dates.
One way could be to create an array of dates based on the start and end dates that you have. Use that array in beforeShowDay to disable the range.
Demo: http://jsfiddle.net/abhitalks/FAt66/1/
For example, Relevant portions of JS:
var startDate = "2014-06-15", // some start date
endDate = "2014-06-21", // some end date
dateRange = []; // array to hold the range
// populate the array
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
// use this array
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [dateRange.indexOf(dateString) == -1];
}
Now, you could set startDate and endDate whenever a date is selected. In the example fiddle I linked to above, the start and end dates are set whenever a date is selected in the two top inputs. The data array is populated when date is selected in the second input.
Note: The above example is additive, i.e. everytime you select a new range it gets added as disabled dates into the target. If you want to clear the existing disabled range before specifying a new range, then you could do a destroy and reattach the datepicker. (And also reset the dateRange array)
Demo 2: http://jsfiddle.net/abhitalks/FAt66/3/
Relevant portion of JS:
$("#dt").datepicker("destroy");
$("#dt").datepicker({
dateFormat : 'yy-mm-dd',
beforeShowDay: disableDates
});
var disableDates = function(dt) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', dt);
return [dateRange.indexOf(dateString) == -1];
}
Looking at your actual code, all you need is this:
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
addWeek($.datepicker.iso8601Week(new Date(dateText)), $.datepicker.formatDate( dateFormat, startDate, inst.settings ), $.datepicker.formatDate( dateFormat, endDate, inst.settings ));
for (var d = new Date(startDate);
d <= new Date(endDate);
d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('dd/mm/yyyy', d));
}
selectCurrentWeek();
},
beforeShowDay: disableDates,
...
This will keep adding the newly selected date ranges to the array and will additively keep on disabling. But, be cautioned that you will need an escape route when an already selected week is removed. In that case, you may work with multiple array which can be coalesced into one master array.
If there is a requirement to disable a list of dates or like if in any reservation kind of projects where we have to disable some dates throughout the process. So you can use following code,
$(function() {
//This array containes all the disabled array
datesToBeDisabled = ["2019-03-25", "2019-03-28"];
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
minDate : 0,
todayHighlight: 1,
beforeShowDay: function (date) {
var dateStr = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [datesToBeDisabled.indexOf(dateStr) == -1];
},
});
});
I used all the solutions but not worked but i made change in common jquery.datepick.js
Exisiting _isSelectable constructor function
_isSelectable: function(elem, date, onDate, minDate, maxDate) {
var dateInfo = (typeof onDate === 'boolean' ? {selectable: onDate} :
(!$.isFunction(onDate) ? {} : onDate.apply(elem, [date, true])));
//This function is modified by Savata to Block fridays on homepage
return (dateInfo.selectable !== false) &&
(!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime());
}
Changed to
_isSelectable: function(elem, date, onDate, minDate, maxDate) {
var dateInfo = (typeof onDate === 'boolean' ? {selectable: onDate} :
(!$.isFunction(onDate) ? {} : onDate.apply(elem, [date, true])));
return (dateInfo.selectable !== false) &&
(!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) && date.getDay() != 5;
/*Added last condition date.getDay() != 5 to block friday
In your case change accordingly
for sunday = 0 to saturday = 6
*/ }

Categories