js datepicker - allow non-consecutive days pcm - javascript

I would like to limit users to selecting only the first and third Monday of each month. We have a volunteer intake only on these days, so I want to limit incorrect date selections as much as possible.
I'm not a js coder, but have managed to adapt some code I found online to allow the first or third Monday of each month, but I can't work out how to allow both of them.
Here's the code I have for the first Monday:
var firstMonday = new Date(date);
var mondays=0;
firstMonday.setDate(1);
while (mondays < 1) {
firstMonday.setDate(firstMonday.getDate() + 1);
if (firstMonday.getDay() == 1) {
mondays++;
}
}
var result = date.getDate() != firstMonday.getDate();

I think this is what you are asking. Credit to jabclab for the getMondays() function.
// test: first monday of this month
// result: true
//var dates = [new Date(2017,8,4)];
// test: third monday of this month
// result: true
//var dates = [new Date(2017,8,18)];
// test: first and third monday of this month
// result: true
var dates = [new Date(2017,8,4), new Date(2017,8,18)];
// test: first monday, third monday, and random day from this month
// result: false
//var dates = [new Date(2017,8,4), new Date(2017,8,18), new Date(2017,8,22)];
alert(validate(dates));
function validate(dates) {
var valid = true;
var mondays = getMondays();
var firstMonday = mondays[0].setHours(0,0,0,0);
var thirdMonday = mondays[2].setHours(0,0,0,0);
if (dates && dates.length > 0) {
for (var i = 0; i < dates.length; i++) {
// Zero out time so only year, month, and day is compared
var d = dates[i].setHours(0,0,0,0);
if (d != firstMonday && d != thirdMonday) {
return false;
}
}
}
else {
valid = false;
}
return valid;
}
function getMondays() {
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}

Thanks, but I'm not sure if the above works or not as I was looking for a js code answer - I'll leave that for someone else to work out.
...which I've found in the meantime. Many thanks to Hugh at Fabrik for the following:
var thisdate = new Date(date);
thisdate.setHours(0,0,0,0);
var day = 1; // monday
var nth = 1; // first
var first = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1),
add = (day - first.getDay() + 7) % 7 + (nth - 1) * 7;
first.setDate(1 + add);
nth = 3; // third
var third = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1),
add = (day - third.getDay() + 7) % 7 + (nth - 1) * 7;
third.setDate(1 + add);
//console.log(thisdate + ', ' + first + ', ' + third);
var result = (first.getTime() !== thisdate.getTime()) && (third.getTime() !== thisdate.getTime());

Related

Convert javascript from single date exclusion to multiple dates

With our limited knowledge we were able to exclude certain dates in a date delivery module based on weekday and time. See code below.
But now we want to exclude all Wednesdays and Saturdays in the next year if you select carrier 99. So multiple disabledDays.push(excldatum) being each Wednesday and Saturday for one year starting from today if this particular carrier is selected.
Can someone please help us how to write that code?
var selected_carrier = parseInt($('.delivery_option_radio:checked').val());
var weekdag = new Date().getDay();
var uur = new Date().getHours();
var vandaag = new Date();
var morgen = new Date();
morgen.setDate(vandaag.getDate() + 1);
var exclmaand = morgen.getMonth() + 1;
var excldag = morgen.getDate();
var excldatum = exclmaand + "-" + excldag;
// carrier is postnl
if (selected_carrier == 99) {
// weekdag 0 is zondag t/m 6 is zaterdag
if (weekdag > -1 && weekdag < 5) {
// na 23 uur
if (uur >= 23) {
disabledDays.push(excldatum);
}
}
}
if (selected_carrier == 99) {
// weekdag 5 is vrijdag
if (weekdag == 5) {
// na 10 uur
if (uur >= 10) {
disabledDays.push(excldatum);
}
}
}
Something like the following piece of code might work for you. It gets all dates for the specified weekdaysToProcess for the next 365 days starting today. Eg. [3,6] for Wednesday and Saturday.
You can add any other filtering you like of course.
function GetDatesForWeekdaysForNext365Days(weekdaysToProcess) {
var currentDate = new Date();
var foundDates = [];
for (var day = 0; day < 365; day++) {
var calculatedDate = new Date();
calculatedDate.setDate(currentDate.getDate() + day);
var calculatedWeekDay = calculatedDate.getDay();
if (weekdaysToProcess.includes(calculatedWeekDay)) {
foundDates.push(calculatedDate);
}
}
return foundDates;
}
The function can be called for carrier 99 like:
disabledDays = GetDatesForWeekdaysForNext365Days([3,6]);

Calculating weekends within a month

I want to build a simple function that would receive a particular month to check. In return it would provide the amount of weekend days it counted within that month.
In the code I'm assuming that the current year is the relevant year to simplify the task.
The problem is it's not return the proper answer for weekends in reality when going over a calendar and counting it manually.
workDays(4); // submitting the month to check for
function workDays(monthCheck) //Calculate the actual work days: eliminate weekends from month
{
// init month to check as proper date variable and setting days to 0 for total days
var month = new Date(new Date().getFullYear(), monthCheck+1, 0);
var daysOff = 0; //init
for(i = month.getDate(); i>=0; i--) //check for days that = 0 or 6 (Sunday OR Saturday)
{
if(new Date(month.getFullYear(), monthCheck, i).getDay() == 0 || new Date(month.getFullYear(), monthCheck, i).getDay() == 6)
{
console.log(daysOff++); // weekend day added to weekend days counter
}
}
return console.log("The days off for the month of " + (month.getMonth()) + " are " + daysOff + " days off.");
}
I find your logic very confusing. I refactored the code to an (imo) more readable version, and the result seems as expected:
nonWorkDays(4);
function nonWorkDays(month)
{
var current = new Date(new Date().getFullYear(), month - 1, 1);
var daysOff = 0; //init
// as long as our date is in the requested month
while (current.getMonth() == month -1) {
// saturday or sunday?
if (current.getDay() == 0 || current.getDay() == 6) {
daysOff++;
console.log(daysOff, current);
}
// move to next day
current.setDate(current.getDate() + 1);
}
console.log("The days off for the month of " + month + " are " + daysOff + " days off.");
return daysOff;
}
And a fiddle to demonstrate: https://jsfiddle.net/4kmtemfy/
Not sure where you went wrong but this seems right:
var d = new Date();
var getTot = daysInMonth(d.getMonth(),d.getFullYear());
var weekends = new Array();
for(var i=1;i<=getTot;i++){
var newDate = new Date(d.getFullYear(),d.getMonth(),i)
if(newDate.getDay()==0 || newDate.getDay()==6){
weekends.push(i)
}
}
console.log(weekends.length);
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
Your issue is with monthCheck+1. Since months are zero indexed and you want the month number of the following month, don't subtract 1. You can also simplify the logic somewhat:
function workDays(monthCheck) {
// Create date for last day of month to check
var month = new Date(new Date().getFullYear(), monthCheck, 0);
var daysOff = 0;
// For each day of the month
for(var i = month.getDate(); i>=0; i--) {
// Add day off for Saturday and Sunday
if (!(month.getDay()%6)) {
daysOff++;
}
month.setDate(month.getDate()-1);
}
return daysOff;
}
var month = 4;
console.log('Days off for ' + month + ' are ' + workDays(month) + '.');

Javascript function , which takes a month/date and disply 12 months/dates back

Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"

How can I add n days to a date but exclude Sundays using yyyymmdd format?

I want a date after 'n' days from a given date in 'yyyymmdd' format (output is also in same format).Adding n days should exclude Sundays. Is it possible to do this in javascript?
Here is my code to add n days to a date
function mydate(dateStr,offset)
{
var ymd = dateStr.match(/^(\d{4})(\d{2})(\d{2})$/);
if (ymd)
{
var date = new Date(ymd[1], ymd[2] - 1, ymd[3]);
date.setDate(date.getDate() + offset);
return $.datepicker.formatDate('yymmdd', date);
}
else
{ // parse error
return null;
}
}
for example,
mydate('19890831',10)
will return
19890910
but actually what I need is '19891012' because there are 2 Sundays when we add 10 days to the '19890831'
Simple solution; you can just loop through the days and skip sundays:
while (offset > 0) {
date.setDate(date.getDate() + 1);
if (date.getDay() != 0) offset--;
}
You can refer to answer here to figure out how many sundays are there between two dates once you have that you can simply add that number to your original days diff.
How to determine number Saturdays and Sundays comes between two dates in java script
function pad(n){
if(n < 10){
return "0" + n;
}
return n;
}
function addDays(dt, n){
var matches = dt.match(/^(\d{4})(\d{2})(\d{2})$/);
var year = matches[1];
var month = matches[2];
var day = matches[3];
var dt = new Date(year, month - 1, day);
var weekDay = dt.getDay();
if((weekDay + n) > 6){
n = n + 1;
}
if(weekDay === 0){
n = n + 1;
}
var oneDayInMillis = 1 * 24 * 60 * 60 * 1000;
var newDt = new Date(dt.getTime() + (oneDayInMillis * n));
return "" + newDt.getFullYear() + pad(newDt.getMonth() + 1) + pad(newDt.getDate());
}

Calculate days of the week from Monday to Saturday

In my form I have a datafield where I select the day of the week!
For example if I select today 23-03-2012 Friday, I need to get an array of days from previous Monday to this next Saturday.
array:
[0],[19-03-2012],[Monday]
[1],[20-03-2012],[Monday]
[2],[21-03-2012],[Wednesday]
[3],[22-03-2012],[Monday]
[4],[23-03-2012],[Friday]
[5],[24-03-2012],[Saturday]
How can i do it for any selected day of the week obviously paying attention to changes?
Thanks
This function will return an array of all the dates in the week of date, Monday to Saturday.
function GetDaysOfWeek(date)
{
var days = new Array();
for (var i = 0; i < 6; i++)
{
days[i] = new Date(date.getYear(),
date.getMonth(),
date.getDate() - date.getDay() + 1 + i);
}
return days;
}
mayby try out MomentJs: http://momentjs.com/docs/
some examples:
moment().day(-7); // set to last Sunday (0 - 7)
moment().day(7); // set to next Sunday (0 + 7)
moment().day(10); // set to next Wednesday (3 + 7)
moment().day(24); // set to 3 Wednesdays from now (3 + 7 + 7 + 7)
For display the current day of the week:
var now = new Date();
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.write("Today is " + dayNames[now.getDay()] + ".");
First find todays date
Find the last monday (including today)
Show that date, and the next 5 days after it (Tuesday-Saturday)
var d = new Date();
if (d.getDay()==0){
d.setDate(d.getDate() + 1);
}
​while (d.getDay() != 1){
d.setDate(d.getDate() - 1);
}
var days = new Array();
for (var i = 0; i < 6; i++){
days[i] = d.getDate() + i;
}
return days;
try this :
var dayString = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var now = new Date();
var currentDay = now.getDay(); // return 0 for Sunday, 6 for Saturday
var result = [];
var tempDate = new Date(now.getTime());
tempDate.setDate(now.getDate()-(currentDay+6)%7); // now tempDate is previous Monday
while(tempDate.getDay()!=0) {
var currentMonth = tempDate.getMonth()+1;
if(currentMonth<10) currentMonth = "0"+currentMonth;
result.push([tempDate.getDay()-1,tempDate.getDate()+"-"+currentMonth+"-"+tempDate.getFullYear(),dayString[tempDate.getDay()]]);
tempDate.setDate(tempDate.getDate()+1);
}
console.log(result);
Something like the following will do the trick, I"m sure you can get the formatting to where you want it.
// Assuming d is a date object
function getDateArray(din) {
// Add leading zero to one digit numbers
function aZ(n){return (n<10? '0':'') + n;}
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var d = new Date(din); // Don't wreck input date
var dn = d.getDay();
var a = [];
var i = 6; // length of day array
if (!dn) {
// It's Sunday, what now?
return ['Sunday!'];
}
d.setDate(d.getDate() + 6 - dn); // Next Saturday
do {
a[i--] = i + ' ' + aZ(d.getDate()) +
'-' + aZ(d.getMonth() + 1) +
'-' + d.getFullYear() +
' ' + days[d.getDay()];
d.setDate(d.getDate() - 1);
} while (i);
return a;
}
// Test it
var date = new Date(2012,2,2)
alert( date + '\n\n' + getDateArray(date).join('\n'));
/*
Fri Mar 02 2012 00:00:00
0 27-02-2012 Monday
1 28-02-2012 Tuesday
2 29-02-2012 Wednesday
3 01-03-2012 Thursday
4 02-03-2012 Friday
5 03-03-2012 Saturday
*/

Categories

Resources