jQuery DatePicker - Choose Next Weekday if Current Date Falls on Weekend - javascript

I know how to gray out the weekends on the jQuery Datepicker by instantiating it like this:
$('.calendar').datepicker({ beforeShowDay: $.datepicker.noWeekends });
The Datepicker also automatically selects the current date, so if the current date happens to be on a weekend, nothing is selected.
How can I make it select the next weekday if the currentdate falls on a weekend?
Thanks a lot!
Al

You can loop through and find the next valid date based on whatever beforeShowDay function you're using and set the defaultDate property to the result, like this:
var sd = new Date();
for(var i = 0; i < 7; i++) {
if($.datepicker.noWeekends(sd)[0]) break; //found a valid day, hop out
sd.setDate(sd.getDate() + 1); //move to the next day
}
$('.calendar').datepicker({
beforeShowDay: $.datepicker.noWeekends,
defaultDate: sd
});
Here's a demo that works for today (otherwise you could only see it work on weekends :)

Related

JQuery datetimepicker exception day with minDate and maxDate

I'm facing a issue with datetimepicker.
I have a page with an Order, that has a delivery date.
Whenever the Order is listed, the datetimepicker has a certain value (for example, some day last week.) I want to be able to edit it but only select a set of avaiable dates (from today up to 30 days including "some day last week").
How should I proceed?
Function of the picker:
var maxdate = new Date();
maxdate.setDate(maxdate.getDate() + 30);
var $p = jQuery.noConflict();
$p("#foo").datetimepicker({
format: 'YYYY/MM/DD',
useCurrent:true,
showClose:true,
defaultDate: $.now(),
minDate: moment().millisecond(0).second(0).minute(0).hour(0),
maxDate:maxdate,
});
EDIT:
I'm guessing i wasn't very explicit with my question.
Example for what i want:
minDate = 2017/10/14
maxDate = 2017/10/30
(at this point everything works fine)
Date option that i want to pick = 2017/09/10 (that is 1 month older than minDate) without changing minDate!
I want to create an exception date that is not inside the range of min/max date.
For the options showed I guess you are using eonasdan-datetimepicker.
So proceed like this:
var maxDate = moment().add(30, 'day');
var $p = jQuery.noConflict();
$p("#foo").datetimepicker({
format: 'YYYY/MM/DD',
useCurrent: true,
showClose: true,
defaultDate: $p.now(),
minDate: moment().startOf('day'),
maxDate: maxDate,
});
Where maxDate will have 30 days added using moment method .add()
for minDate It is easier if you use startOf('day') as will be the same you have, but easier to read.
EDIT
Ok so what you want is to allow your users to choose a "special day" that is not in the array, so for that you could use enabledDates option.
In which you will add your special day and the range of the days enabled, so only thus will be allowed to be selected and would be something like this:
let currentFormat = 'YYYY/MM/DD';
let specialDay = '2017/09/10';
let maxDate = moment().add(30, 'day'); //To the picker not allow to go further in the view
let startDate = moment().startOf('day').format(currentFormat); //First date being added, current day
let enabledDates = [
moment(specialDay, currentFormat), //this is our "special day"
moment(startDate, currentFormat) // we format the date to the format needed ];
//Iterate and add 30 days, and only those will be able to be picked
for (var i = 1; i <= 30; i++) {
//apply the format
let date = moment().add(i, 'day').format(currentFormat);
enabledDates.push(moment(date, currentFormat));
}
//We init our picker with the 30 days and our special date
//`minDate` and `maxDate` still there to give the style to the view
$("#myDatepicker").datetimepicker({
format: currentFormat,
useCurrent: false,
showClose: true,
minDate: moment(specialDay, currentFormat),
maxDate: maxDate,
enabledDates: enabledDates,
});
Working fiddle https://jsfiddle.net/William_/2ze7bo27/
Edit: Make easier to change format and special date

eternicode bootstrap-datepicker - add one day to senond date without moment.js

I wanted to ask, if is possible to add one day to second datepicker, while selecting date in first datepicker.
Below some piece of code, part with comment, shows when this event is.
This code works fine, but i want to add one day, on first datepicker update.
Now this code update second datepicker with exact value of first one.
Is this possible without moment.js ?
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('.date-1').datepicker({
startDate: now,
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (selected) {
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
// This code updates second datepicker, but should add + 1 day to this date.
$('.date-2').datepicker('setStartDate', startDate);
$('.date-2').datepicker('setDate', startDate);
}).data('datepicker');

MomentJS range not always including current month in date range

For some odd reason, MomentJS range does not always display the current month. I am wondering if there is an option that needs to be set so that it includes the current month in it's date range.
This is the code used to generate the date range. I've also attached a codepen so you can see it in action.
http://codepen.io/anon/pen/rORmxY
//momentJs creates the ranges
//Only shows April 2015
var end = moment("2015-05-01","YYYY-MM-DD");
//where the day is > 18 it Shows May 2015
var end2 = moment("2015-05-19","YYYY-MM-DD");
var start = moment().subtract(1.5, "year");
var range = moment.range(start, end);
var range2 = moment.range(start, end2);
//iterate through the months, and populate the SELECT box
range.by('months', function(date) {
//add those values to a SELECT box
$('#month-range').prepend($('<option>', {
value: date.format("MMM YYYY"),
text: date.format("MMM YYYY")
}));
});
//iterate through the months, and populate the SELECT box
range2.by('months', function(date) {
//add those values to a SELECT box
$('#month-range2').prepend($('<option>', {
value: date.format("MMM YYYY"),
text: date.format("MMM YYYY")
}));
});
Thanks a lot
The work around I've found is to simply tell momentJs to use the end of the month for the range. Which makes sense in this context. This is done by adding .endOf("month") to the end range.
See this code for clarification:
//momentJs creates the ranges
//adding .endOf("month") will Include the month of May in the month ranges
var end = moment("2015-05-01","YYYY-MM-DD").endOf("month");
var start = moment().subtract(1.5, "year");
var range = moment.range(start, end);
//iterate through the months, and populate the SELECT box
range.by('months', function(date) {
//add those values to a SELECT box
$('#month-range').prepend($('<option>', {
value: date.format("MMM YYYY"),
text: date.format("MMM YYYY")
}));
});
Thanks a lot for the help
Please take a look at the source code of month-range (https://github.com/gf3/moment-range/blob/master/lib/moment-range.js).
The reason that setting end date to 2015-05-18 will include one less month as 2015-05-19 is nothing special. It is because today is 2015-11-18 and you set the start date to be 2014-05-18.
Now look at _byString function in moment-range (which is called by 'by' function).
function _byString(interval, hollaback, exclusive) {
var current = moment(this.start);
while (this.contains(current, exclusive)) {
hollaback.call(this, current.clone());
current.add(1, interval);
}
}
'current' variable starts from '2014-05-18' and increases one month at a time.
If the end date is 2015-05-19, 'this.contains()' simply returns true when 'current' = '2015-05-18'. And if end date is 2015-05-19, 'this.contains' will return false. This is the reason for the behavior of your code.
Now, if you wanna always include the current month, I think you always add 1 day to the end date. However, I image this method might cause some problem for the last day of a month. Or you can always set the end date to the first day of the next month, but exclude that month. You can do some experimentation.
Hope this helps!

JQuery datepicker return weeknumber and day of week

Im trying to get the weeknumber and the name/shortcut of the weekday according to the chosen date through a JQuery calendar.
Im not really proficient in JQuery so i can get the weeknumber, but i cant seem to get the name of the day with it.
Could anyone help me out?
$('#datepicker').datepicker({
onSelect: function (dateText, inst) {
$('#weekNumber').val($.datepicker.iso8601Week(new Date(dateText)));
}
});
you have to get the date, than extract the name of the day from it:
var date = $(this).datepicker('getDate');
alert($.datepicker.formatDate('DD', date));
hope it helps!
edit: you can find the working fiddle here.
You can add in your existing block to grab the day name, by using the format date syntax, found in the datepicker documentation, here:
http://api.jqueryui.com/datepicker/#utility-formatDate
In this case, full day name is obtained from 'DD', so your updated code might look like:
$('#datepicker').datepicker({
onSelect: function (dateText, inst) {
var d = new Date(dateText);
$('#weekNumber').val($.datepicker.iso8601Week(d));
$('#dayName').val($.datepicker.formatDate('DD', d));
}
});
Fiddle here: http://jsfiddle.net/duffmaster33/zL6m2wck/
Here is alot of information on how to use the javascript Date object.
Here is the code I suggest you:
$(function() {
$( "#datepicker" ).datepicker({
onSelect: function( dateText, dateObj ){
//You can get your date string that way
console.log(dateText);
//You can get a few value about the date, look in your console to see what you can do with that object
//i.e. - console.log(dateObj.selectedDay)
console.log(dateObj);
//You can see the result of the date in string that way
$('.string').append(dateText);
currDate = new Date(dateText);
//You can have a complete Date object using the Date javascript method
console.log(currDate);
//The Date object in javascript provides you all you need then
//Get the number of day in a week, from 0(Sunday) to 6(Saturday)
$('.getday').append(currDate.getDay());
//Create a function to see day Sun - Sat
function getWeekDay(date) {
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
return days[ date.getDay() ]
}
//Then we use it
$('.getweekday').append(getWeekDay(currDate));
}
});
});
You can see my fiddle there:
https://jsfiddle.net/qapw32Lp/
Here is a great source of information you can use also abotu the Date Object:
http://javascript.info/tutorial/datetime-functions

jQuery datepicker minDate variable

I'm usung the jQuery datepicker. In my "EndDate" textbox I'd like to use the date selected from the the "StartDate" textbox + 1. How do I do this?
I tried this but didn't work. In my start date code I had...
test = $(this).datepicker('getDate');
testm = new Date(test.getTime());
testm.setDate(testm.getDate() + 1);
Then in my end date code I had...
minDate: testm,
but the end date still made all the days for the month available.
Edit. I'm curious as to why this doesn't work. In my start date datepicker I have this..
onSelect: function (dateText, inst) {
test = dateText
}
Why can't I come down into my end date datepicker and say, minDate: test?
Edit. Still not working
$(".dateStartDatePickerBox").datepicker({
minDate:'-0d',
onSelect: function(dateText, inst)
{
test = $(this).datepicker('getDate');
testm = new Date(test.getTime());
testm.setDate(testm.getDate() + 1);
$("#dateEndDatePickerBox").datepicker("option", "minDate", testm);
}
});
$(".dateEndDatePickerBox").datepicker({
onSelect: function()
{
}
});
You'll need to set the min date dynamically on the change event of the start date.
Something like:
$("#startDate").change(function() {
test = $(this).datepicker('getDate');
testm = new Date(test.getTime());
testm.setDate(testm.getDate() + 1);
$("#endDate").datepicker("option", "minDate", testm);
});
Answer to the edit:
You cannot do the following:
var test;
$("#myinput").datepicker({
onSelect: function() { test = $(this).datepicker("getdate"); }
});
$("#myotherinput").datepicker({
minDate: test
});
Test is uninitialized at the time that minDate is being set on myotherinput. The process of setting the minDate doubtless requires DOM manipulation which datepicker manages on initialization or when "option" is called. Simply changing the variable that was used for initialization does not effect the already initialized datepicker.
Are you talking setting a max selection date?
StartDate = new Date("March 20, 2010");
EndDate = new Date("March 21, 2010");
$("#datepicker").datepicker({ minDate: StartDate, maxDate: EndDate, defaultDate: StartDate });
Note the maxDate? That won't let you select any days past it ...
The API documentation for the date picker does seem to say it should take a Date object, but I've had this exact problem in the past and this is how I solved it.
Pass minDate an offset, instead of a date. You'll need a function to take your start date, add one to it and then get the offset from today. So you could have a function like:
function offsetFromToday( someDate ) {
// clear time offset because we only want to take date into account
someDate.setHours( 0 );
someDate.setMinutes( 0 );
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
// Convert both dates to milliseconds
someDate = someDate.getTime();
var today = new Date().getTime();
// Calculate the difference in milliseconds
var difference = Math.abs( someDate - today );
// Convert back to days and return
return Math.floor( (difference / ONE_DAY) + 1 );
}
So you just need to get your start date a day ahead: StartDate.setDate( StartDate.getDate() + 1 ) or similar, and then pass it to this function to get an offset, then give that to minDate.

Categories

Resources