Change the start week on Jquery datepicker ShowWeek - javascript

I'm working on a project utilizing the jQuery datepicker, and am trying to use the showWeek attribute to display the week number next to the calender.
My problem is that I don't want 'week 1' to start on the first of January, but instead on the first of August.
Is there any way I can Implement this?
Thanks

working with the next month not working for prev month so i have disabled prev month.
calender always open with August month if current month less than August than calender start from previous year August.
Working Demo http://jsfiddle.net/cse_tushar/dR429/4
$(document).ready(function () {
i = 0;
month_set = 8;
var d = new Date();
week = (Math.ceil(Math.round(((new Date(d.getFullYear() + 1, 1)) - (new Date(d.getFullYear(), 1))) / 86400000) / 7));
current_year = ((d.getMonth() + 1) >= month_set) ? d.getFullYear() : d.getFullYear() - 1;
function myWeekCalc() {
i++;
return i = (i > week) ? 0 : i;
}
$("#d1").datepicker({
showWeek: true,
defaultDate: new Date(current_year, month_set-1, 1),
calculateWeek: myWeekCalc,
onClose: function () {
i = 0;
},
onChangeMonthYear: function (year, month) {
var diff = month - month_set;
var d = new Date(month + ' 1' + ',' + year);
if (d.getDay() != '0') {
i--;
}
if (month == month_set) {
i = 0;
}
if (current_year != year && month == month_set) {
week = (Math.ceil(Math.round(((new Date(year + 1, 1)) - (new Date(year, 1))) / 86400000) / 7));
}
}
}).focus(function () {
$(".ui-datepicker-prev").remove();
});
});

Using jQuery Date Picker custom Week of Year calculation and Moment library to calculate the week of year based on your locale.
Please refer to this working example:
https://jsfiddle.net/amansour/sez8fLgt/
function myWeekCalc(dt) {
var dat = moment(dt).locale("en-US");
return dat.week();
// return dat.isoweek(); // you will have to use firstDay : 1
}
$(function(){
$("[type='date']").datepicker({
changeMonth: true,
changeYear: true,
showWeek: true,
firstDay: 0, // 1 being Monday, 0 being Sunday, 6 being Friday
calculateWeek: myWeekCalc,
dateFormat: "yy-mm-dd",
yearRange: "-12:+12"
});
});

Related

JS Datepicker: Disable past dates + specific days of the week + specific dates

I have a datepicker in JS where I disabled passed dates AND only allow saturdays like this:
$(document).ready(function(){
$("#aankomstdatum").datepicker({
dateFormat: "dd-mm-yy",
numberOfMonths:2,
minDate: 0,
beforeShowDay: function(date){
var day = date.getDay();
return [day == 6];
}});
});
I also have a code that lets me disable specific dates like this:
/** Days to be disabled as an array */
var disableddates = ["26-05-2018"];
function DisableSpecificDates(date) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
// First convert the date in to the mm-dd-yyyy format
// Take note that we will increment the month count by 1
var currentdate = (m + 1) + '-' + d + '-' + y ;
// We will now check if the date belongs to disableddates array
for (var i = 0; i < disableddates.length; i++) {
// Now check if the current date is in disabled dates array.
if ($.inArray(currentdate, disableddates) != -1 ) {
return [false];
}
}
}
With adding this, it works:
beforeShowDay: DisableSpecificDates
The issue I have is that i can't make both work. I'm not sure How can disable the past dates and all days except saturdays AND also disable specific given dates in the array, while seperatly they do work. I always get syntax errors when trying for example:
beforeShowDay: DisableSpecificDates, function(date){
var day = date.getDay();
return [day == 6];
}});
Is this possible to do?
Yes, it's possible to achieve this. You want to create one function and return [false] from it if:
date is a Saturday or
date is contained within disableddates array
Here's the example:
var disableddates = ["26-04-2018"];
function DisableDates(date) {
var selectable = !isSaturday(date) && !isDateDisabled(date);
return [selectable];
}
function isSaturday(date) {
var day = date.getDay();
return day === 6;
}
function isDateDisabled(date) {
var m = date.getMonth() + 1;
var d = date.getDate();
var y = date.getFullYear();
// First convert the date in to the dd-mm-yyyy format
if(d < 10) d = '0' + d;
if(m < 10) m = '0' + m;
var currentdate = d + '-' + m + '-' + y;
// Check if disableddates array contains the currentdate
return disableddates.indexOf(currentdate) >= 0;
}
And then just pass DisableDates function as the value of your beforeShowDay option:
$("#aankomstdatum").datepicker({
dateFormat: "dd-mm-yy",
numberOfMonths:2,
minDate: 0,
beforeShowDay: DisableDates
});

How do i use javascript to return the number of days holidays between two dates excluding holidays?

I have a code that returns the number of days between two dates selected with jquery datapicker.
I would like to add a function for holidays that will exclude all holidays in an array;
var holidays [25-12-2016,26-12-2016,1-1-2017];
please find code below:
<script>
<!--Calculate Leave days excluding weekends
function calcBusinessDays(start, end) {
// This makes no effort to account for holidays
// Counts end day, does not count start day
// make copies we can normalize without changing passed in objects
var start = new Date(start);
var end = new Date(end);
// initial total
var totalBusinessDays = 0;
// normalize both start and end to beginning of the day
start.setHours(0,0,0,0);
end.setHours(0,0,0,0);
var current = new Date(start);
current.setDate(current.getDate() + 1);
var day;
// loop through each day, checking
while (current <= end) {
day = current.getDay();
if (day >= 1 && day <= 5) {
++totalBusinessDays;
}
current.setDate(current.getDate() + 1);
}
return totalBusinessDays;
}
$(function() {
$( "#start_date" ).datepicker({ minDate:0, showOn: 'button', buttonImageOnly: true, buttonImage: 'images/calendar.png', beforeShowDay: $.datepicker.noWeekends });
$( "#end_date" ).datepicker({ minDate:0, showOn: 'button', buttonImageOnly: true, buttonImage: 'images/calendar.png',beforeShowDay: $.datepicker.noWeekends,
onSelect: function (dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+12M'); // Set other max, default to +18 months
var start = $("#start_date").datepicker("getDate");
var end = $("#end_date").datepicker("getDate");
var days = (end - start) / (1000 * 60 * 60 * 24);
var diff = calcBusinessDays(start,end);
$("#leave_days").val(diff);
} });
});
</script>
<input name="start_date" type="text" id="start_date" />
<input name="end_date" type="text" id="end_date" />
<input name="leave_days" type="text" id="leave_days" size="32" class="form-control"/>
Like said in comments, you will have to define the holiday array.
For this example, I defined two dates: 2016-11-23 and 2016-12-02
You can use a database or do it manually in script in order to maintain the relevant dates over time.
This part is not explained here, but in the script, I used the default MySQL date format, which is YYYY-MM-DD.
It it should be easy to get holiday dates from a database.
An additionnal function is used to convert current date into this MySQL date format, in order to compare it.
Then, in the while loop, we check if the date is a holiday and, if so, set a boolean flag used in the condition to add a "business day" or not to the counter.
var holiday_array=["2016-11-23", "2016-12-02"]; // YYYY-MM-DD (Default MySQL date format)
function dateToMySQL (x){
var MySQL_day = x.getDate();
if(MySQL_day<10){
MySQL_day = "0"+MySQL_day; // Leading zero on day...
}
var MySQL_month = x.getMonth()+1; // Months are zero-based.
if(MySQL_month<10){
MySQL_month = "0"+MySQL_month; // Leading zero on month...
}
var MySQL_year = x.getYear()+1900; // Years are 1900 based.
var MySQL_date = MySQL_year+"-"+MySQL_month+"-"+MySQL_day;
return MySQL_date;
}
function calcBusinessDays(start, end) {
// This makes no effort to account for holidays
// Counts end day, does not count start day
// make copies we can normalize without changing passed in objects
var start = new Date(start);
var end = new Date(end);
// initial total
var totalBusinessDays = 0;
// normalize both start and end to beginning of the day
start.setHours(0,0,0,0);
end.setHours(0,0,0,0);
// Prepare loop's variables
var current = new Date(start);
current.setDate(current.getDate() + 1);
var day;
var holidayFound=false;
// loop through each day, checking
while (current <= end) {
//console.log("current: "+current);
// Check if current is in the holiday array
var MySQLdate = dateToMySQL(current);
console.log("MySQL date: "+MySQLdate);
if($.inArray(MySQLdate,holiday_array)!=-1){
console.log(" ^----------- Holiday!!!");
holidayFound=true; // "flag"
}
// If current is monday to friday and NOT a holiday
day = current.getDay();
if (day >= 1 && day <= 5 && !holidayFound) {
++totalBusinessDays;
}
// For next iteration
current.setDate(current.getDate() + 1);
holidayFound=false;
}
return totalBusinessDays;
}
$(function() {
$( "#start_date" ).datepicker({
minDate:0,
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'http://www.nscale.net/forums/images/misc/Tab-Calendar.png', //'images/calendar.png',
beforeShowDay: $.datepicker.noWeekends
});
$( "#end_date" ).datepicker({
minDate:0,
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'http://www.nscale.net/forums/images/misc/Tab-Calendar.png', //'images/calendar.png',
beforeShowDay: $.datepicker.noWeekends,
onSelect: function (dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+12M'); // Set other max, default to +18 months
var start = $("#start_date").datepicker("getDate");
var end = $("#end_date").datepicker("getDate");
var days = (end - start) / (1000 * 60 * 60 * 24);
var diff = calcBusinessDays(start,end);
$("#leave_days").val(diff);
}
});
});
See in CodePen ( Check the console ;) )
You can use this logic:
Taking weekends as holidays inbetween
function workingDaysBetweenDates(startDate, endDate) {
var millisecondsPerDay = 86400 * 1000;
startDate.setHours(0,0,0,1);
endDate.setHours(23,59,59,999);
var diff = endDate - startDate;
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay === 0 && endDay != 6)
days = days - 1 ;
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay === 6 && startDay !== 0)
days = days - 1 ;
return days;
}
var a = new Date(2015, 10, 16);
var b = new Date(2016, 01, 20);
var t = workingDaysBetweenDates(a,b);
alert(t);
Hope this helps!

JavaScript code returning NaN instead of numeric value

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

How to Disable the very next weekends in jQuery UI Datepicker?

In an order page I want to implement a calendar, in which, if the user is ordering on friday after 10am, then block the following saturday and sunday in delivery date calendar. Here is a sample code I am trying, but not working as intended.
beforeShowDay: function(date) {
var day = dt.getDay();
var hour = dt.getHours();
if (day == 4) {
// i think, here i want to put the code to disable days
}
}
If I use something like this
beforeShowDay: function(date) {
var day = date.getDay();
var dt = new Date();
var hour = dt.getHours();
return [(day != 5 && day != 6)];
}
I am able to disable Sat and Sun days, but this will disable all the Sat and Sun days. I wnat to disable only the very next Sat n Sun days to be disabled. Also I can get current Hour in var hour, So where should I use the condition to check if the hour is greater than 10am, I am using something like this but not working
beforeShowDay: function(date) {
var dt = new Date();
var hour = dt.getHours();
var day = date.getDay();
if (day == 4 && hour >= 10) {
return [(day != 5 && day != 6)];
}
}
Inside the beforeShowDay function, check the current date to see if it is a Friday and after 10am. If this is true then you also need to check if the date passed as argument is the next Saturday or Sunday:
$(function() {
$("#datepicker").datepicker({
beforeShowDay: function(date) {
// date (Friday March 13 2015 10:00 AM) is hardcoded for testing
var now = new Date(2015, 3 - 1, 13, 10, 0, 0, 0);
if (now.getDay() === 5 && now.getHours() >= 10) {
var now_plus_1 = new Date(now.getTime()); now_plus_1.setHours(0, 0, 0, 0); now_plus_1.setDate(now_plus_1.getDate() + 1);
var now_plus_2 = new Date(now.getTime()); now_plus_2.setHours(0, 0, 0, 0); now_plus_2.setDate(now_plus_2.getDate() + 2);
return [date.getTime() !== now_plus_1.getTime() && date.getTime() !== now_plus_2.getTime(), ""];
}
return [true, ""];
}
});
});
#import url("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-darkness/jquery-ui.min.css");
body { font-size: smaller; }
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input id="datepicker">
$('#datepicker').datepicker({
beforeShowDay: function(date){
var dt = new Date(),
day = dt.getDay(),
hour = dt.getHours(),
twoDaysFrmNow = new Date().setDate(dt.getDate() + 2);
return [!(day == 5 && hour >= 10 && date <= twoDaysFrmNow && date > dt)];
}
});
beforeShowDayType: Function( Date date )
Default: null
A function that takes a date as a parameter and must return an array
with:
[0]: true/false indicating whether or not this date is selectable [1]:
a CSS class name to add to the date's cell or "" for the default
presentation [2]: an optional popup tooltip for this date
The function is called for each day in the datepicker before it is
displayed.
beforeShowDay: function(date) {
var day = dt.getDay();
var hour = dt.getHours();
if( day == 4) {
// this is an example of how to use
//first parameter is disable or not this date
//second parameter is the class you want to add ( jquery will remove the click listener, but you probebly want to style it like this date is not available
//third optional tootltip like 'closed on weekends'
return [false,'disabled','weekend']
}
}

disable jQuery DatePicker dates

I have attempted to enable selection of only the first date of each month in a jQuery datepicker. The possible dates are listed in var enabledates.
var enabledDays = ["6-1-2013", "7-1-2013", "8-1-2013",
"9-1-2013", "10-1-2013", "11-1-2013"];
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < enabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y, enabledDays) != -1
|| new Date() > date) {
return [true];
}
}
return [false];
}
$(function(){
$.datepicker.setDefaults($.extend($.datepicker.regional["ru"]));
$("#datepicker1, #datepicker2, #datepicker3").datepicker({
dateFormat: "yy-mm-dd",
duration: "normal",
numberOfMonths: [ 1, 2 ],
constrainInput: true,
beforeShowDay: nationalDays
});
});
How can I apply this first date constraint to the whole calendar?
If you just want to enable a range I would say you can use the Option properties minDate an maxDate.
Regarding your Problem to enable all Dates from an array. Please have a look at this fiddle http://jsfiddle.net/uYe9X/
function available(date) {
var dt= date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if (availableDates.indexOf(dt) !== -1) {
return [true, "","available"];
} else {
return [false,"","not available"];
}
}
As Pedro mentioned you could use the beforeShowDay Callback to reference a function which computes if the day should be enabled. The callback is used for every day which is displayed in the datepicker.
http://api.jqueryui.com/datepicker/#option-beforeShowDay

Categories