How I can find second and fourth Saturday in JavaScript fullcalender api, so that I can highlight those 2nd and 4th Saturday with "week Day Off" event name?
Fullcalendar_screenshot
You need to find all saturdays in current month. Then filter by odd index since 2th and 4th are 1 and 3 indexes.
Now you can highlight day that matched.
function getSaturdays(year, month) {
let day, date;
let saturdays = [];
day = 1;
date = new Date(year, month, day);
while (date.getMonth() === month) {
if (date.getDay() === 6) { // Sun=0, Mon=1, Tue=2, etc.
saturdays.push(new Date(year, month, day).getDate());
}
day += 1;
date = new Date(year, month, day);
}
return saturdays;
}
let saturdays = getSaturdays(2021, 5).filter((day, index) => index % 2 !== 0)
console.log(saturdays)
Original answer
//Here instead of arrayOfDaysInMonth variable you can pass javascript dates according to month here i have passed statically
var arrayOfDaysInMonth = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28];//feb
var saturdays = [2,4] // 2nd and 4th saturday;
var secondWeekOfCount = [];
var whichDateIsSecondorFourthSat=[];
arrayOfDaysInMonth.map((i)=>{
var myDate = new Date();
myDate.setFullYear(2022);
myDate.setMonth(1); // Feb
myDate.setDate(i);
if(myDate.getDay() === 6){
secondWeekOfCount.push(i);
saturdays.map((d)=>{
if(d ===secondWeekOfCount.length ){
whichDateIsSecondorFourthSat.push(i)
}
})
}
})
console.log(whichDateIsSecondorFourthSat)// This will be your result
Related
I know that I can use this for the start of the month moment().startOf('month') but I need the first Sunday of the month.
You could do this:
function getFirstWeekDay(dateString, dayOfWeek) {
var date = moment(dateString, "YYYY-MM-DD");
var day = date.day();
var diffDays = 0;
if (day > dayOfWeek) {
diffDays = 7 - (day - dayOfWeek);
} else {
diffDays = dayOfWeek - day
}
console.log(date.add(diffDays, 'day').format("YYYY-MM-DD"));
}
//Pass in the first of a given calendar month and the day weekday
getFirstWeekDay("2016-10-01", 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
Please check this Code.
var d = new Date();
var first_week = d.getDate();
var the_day = d.getDay();
if(first_week <= 7 && the_day == 0)
{
// It's the first Sunday of the month
// Do more stuff here
}
Here is the sample using js to get the first sunday of any month or year
function firstSunday(month, year) {
let tempDate = new Date();
tempDate.setHours(0,0,0,0);
// first SUNDAY of april
tempDate.setMonth(month);
tempDate.setYear(year);
tempDate.setDate(1);
let day = tempDate.getDay();
let toNextSun = day !== 0 ? 7 - day : 0;
tempDate.setDate(tempDate.getDate() + toNextSun);
return tempDate.toDateString();
}
console.log("april first sunday" , firstSunday(3 , 2020));
console.log("oct first sunday" , firstSunday(9 , 2020))
We have requirement that we need to pass the current date and get the start date of the week. While doing this the start day is user defined like if the user defines the start day as 0 ,day of the week will be sunday,if 1 then start day will be monday and like wise..
We tried the solution from the link Start day of the Week
But it only handles monday or sunday.
I tried the following code but it will fail select friday or saturday ,it will break
var startDate = 5;
if (!d) return;
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day;
var sunday = new Date(d.setDate(diff));
//add days to sunday to adjust sunday,monday,tue,wed...
return new Date(sunday.getYear(), sunday.getMonth(),sunday.getDate()-(7-startDate));
Let me know if any one has idea to do this.
Thanks.
function getStartOfWeek(index) {
var d = new Date();
var day = d.getDay();
var diff = index - day;
if(index > day) {
diff -= 7;
}
return new Date(d.setDate(d.getDate() + diff));
}
document.write(getStartOfWeek(0).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(1).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(2).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(3).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(4).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(5).toLocaleDateString()+"<br/>");
document.write(getStartOfWeek(6).toLocaleDateString()+"<br/>");
This is my "home-made" solution :
getWeekStartDate = function(date)
{
var d = new Date(date);
// Sunday
if (date.getDay() === 0)
return new Date(d.setDate(date.getDate()-6));
// Monday
if (date.getDay() === 1)
return date;
return new Date(d.setDate(date.getDate() - (date.getDay() - 1)));
};
I work with Date objects but of course you can get the day you were looking for with date.getDay()
Hope it helps
I have tried in Jquery and found the solution. Below is the code. It works good.
$first_day_of_the_week = 'Monday';
$start_of_the_week = date('Y-m-d',strtotime("Last $first_day_of_the_week"));
if ( strtolower(date('l')) === strtolower($first_day_of_the_week) )
{
$start_of_the_week = date('Y-m-d',strtotime('today'));
}
echo $start_of_the_week ;
I'm building a chart where the x-axis should be the four weeks of a month. I would like to display only the four Mondays of that month.
I already have the currentMonth and the currentYear variables, and I know how to get the first day of the month. All I need is to get the four Mondays of a month in an array. And all of this in the same JavaScript file.
I'm pretty lost within my programming logic, and I've seen plenty of solutions that don't fit my use case.
Right now, I have:
var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear, currentMonth, 1);
var firstWeekDay = firstDayofMonth.getDay();
but I would like to have something like this:
var myDates = [
new Date(firstMonday),
new Date(secondMonday),
new Date(thirdMonday),
new Date(fourthMonday),
];
The following function will return all Mondays for the current month:
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;
}
This would return the fourth last monday of month [m] in year [y]
function lastmonday(y,m) {
var dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstmonday = false;
while (currentmonth === m){
firstmonday = dat.getDay() === 1 || firstmonday;
dat.setDate(dat.getDate()+(firstmonday ? 7 : 1));
currentmonth = dat.getMonth()+1;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastmonday(2012,3); //=>Mon Mar 26 2012 00:00:00 GMT+0200
lastmonday(2012,2) //=>Mon Feb 27 2012 00:00:00 GMT+0100
lastmonday(1997,1) //=>Mon Jan 27 1997 00:00:00 GMT+0100
lastmonday(2012,4) //=>Mon Apr 30 2012 00:00:00 GMT+0200
To be more generic, this will deliver the last any weekday of a month:
function lastDayOfMonth(y,m,dy) {
var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}
,dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstday = false;
while (currentmonth === m){
firstday = dat.getDay() === days[dy] || firstday;
dat.setDate(dat.getDate()+(firstday ? 7 : 1));
currentmonth = dat.getMonth()+1 ;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastDayOfMonth(2012,2,'tue'); //=>Tue Feb 28 2012 00:00:00 GMT+0100
lastDayOfMonth(1943,5,'fri'); //=>Fri May 28 1943 00:00:00 GMT+0200
For whoever may need, this is a general function to get every monday, tuesday, etc
getDatesOfDayOfWeek (year, month, dayOfWeek) {
const initialDate = new Date(year, month, 1);
const datesOfDayOfWeek = [];
while (initialDate.getDay() !== dayOfWeek) {
initialDate.setDate(initialDate.getDate() + 1);
}
while (initialDate.getMonth() === month) {
const nextDate = new Date(initialDate.getTime());
datesOfDayOfWeek.push(nextDate.getDate());
initialDate.setDate(initialDate.getDate() + 7);
}
return datesOfDayOfWeek;
}
I took Jake's code and generalized it to get the next N occurrences of a particular schedule. (e.g. "Get me the next 10 instances of 2nd Mondays and 1st and 3rd Wednesdays.")
schedule is an object with keys for day-of-week whose values are
an array of the incident within a month that the DoW falls.
keys can include numbers from 1-5, and -1 for "last."
items in a value array can include numbers from 0-6, where 0 is Sunday.
count is optional (defaults to 6) and represents how many items to show.
Samples
First and third Mondays would be nextNthMdays({1: [1, 3]})
Second Wed and Fri would be nextNthMdays({3: [2], 5: [2]})
Last Thursdays would be nextNthMdays({4: [-1]})
function nextNthMdays(schedule, count) {
var d = new Date(),
month = 999,
nthInMonth,
dates = [];
if (count == undefined) {
count = 6;
}
// start at the beginning of the month
d.setDate(1);
// Iterate until we have enough
while (dates.length < count) {
var day = d.getDay();
// Reset counters each month
if (d.getMonth() !== month) {
month = d.getMonth();
nthInMonth = Object.keys(schedule).reduce(function (obj, x) {
obj[x] = 0;
return obj;
}, {});
}
// When you reach an interesting weekday
if (day in schedule) {
// Increment its counter
nthInMonth[day]++;
// If it's after today
if (d > new Date()) {
// and its counter matches
if (schedule[day].indexOf(nthInMonth[day]) !== -1) {
// Add it
dates.push(new Date(d.getTime()));
}
// or if we want the last one
else if (schedule[day].indexOf(-1) !== -1) {
// verify that 7 days from then is a different month
var sevenAway = new Date(d);
sevenAway.setDate(sevenAway.getDate() + 7);
if (d.getMonth() !== sevenAway.getMonth()) {
// Add it
dates.push(new Date(d.getTime()));
}
}
}
}
// Move on to the next day
d.setDate(d.getDate() + 1);
}
return dates;
}
Demonstration
Expand the snippet to run some examples.
// `schedule` is an object with keys
// for day-of-week whose values are
// an array of the incident within
// a month that the DoW falls.
//
// keys can include numbers from
// 1-5, and -1 for "last."
// items in a value array can include
// numbers from 0-6, where 0 is
// Sunday.
//
// `count` is optional (defaults to 6)
// and represents how many items to
// show.
//
// First and third Mondays would be
// nextNthMdays({1: [1, 3]})
// Second Wed and Fri would be
// nextNthMdays({3: [2], 5: [2]})
// Last Thursdays would be
// nextNthMdays(4: [-1])
function nextNthMdays(schedule, count) {
var d = new Date(),
month = 999,
nthInMonth,
dates = [];
if (count == undefined) {
count = 6;
}
// start at the beginning of the month
d.setDate(1);
// Iterate until we have enough
while (dates.length < count) {
var day = d.getDay();
// Reset counters each month
if (d.getMonth() !== month) {
month = d.getMonth();
nthInMonth = Object.keys(schedule).reduce(function (obj, x) {
obj[x] = 0;
return obj;
}, {});
}
// When you reach an interesting weekday
if (day in schedule) {
// Increment its counter
nthInMonth[day]++;
// If it's after today
if (d > new Date()) {
// and its counter matches
if (schedule[day].indexOf(nthInMonth[day]) !== -1) {
// Add it
dates.push(new Date(d.getTime()));
}
// or if we want the last one
else if (schedule[day].indexOf(-1) !== -1) {
// verify that 7 days from then is a different month
var sevenAway = new Date(d);
sevenAway.setDate(sevenAway.getDate() + 7);
if (d.getMonth() !== sevenAway.getMonth()) {
// Add it
dates.push(new Date(d.getTime()));
}
}
}
}
// Move on to the next day
d.setDate(d.getDate() + 1);
}
return dates;
}
console.log('Next third Wednesdays');
console.log(nextNthMdays({3: [3],}));
console.log('Next first and third Mondays');
console.log(nextNthMdays({1: [1, 3],}, 4));
console.log('Next second Wed/Fridays');
console.log(nextNthMdays({3: [2], 5: [2],}, 3));
console.log('Next "Last Thursdays of the month"');
console.log(nextNthMdays({4: [-1],}, 3));
I need Javascript code for a website to automatically adjust a date. The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR 11 a.m. to noon.
Anyone have an idea? Much appreciated!
This function will get you the date object, you can pull out what you need from it:
var getMeeting = function(year, month){
var date = new Date(year, month, 1, 0, 0, 0, 0);
date.setDate(14-date.getDay());
return date;
};
alert(getMeeting(2011,5));
I didn't test but here is the basics:
//our main code
var Months = ["Jan", "Feb", "Mar", /*... you finish... */ ];
var meetingDate = getMonthlyMeeting();
document.Write( "<i>Next membership meeting:</i> Saturday, " + Months[meetingDate.getMonth()] + ", " + meetingDate.getDay() + ", " + meetingDate.getYear() + " 11 a.m. to noon.");
// call this to get the monthly meeting date
// returns a Date() object
function getMonthlyMeeting(){
var today = new Date(); //JS automatically initializes new Date()s to the current time
//first, see if today is our meeting day
var meetingDate;
var thisMonthsMeeting = getSecondTuesdayInMonth(today.getMonth(), today.getYear());
if( thisMonthsMeeting.getDay() == today.getDay() ){
// today is our meeting day!
meetingDate = today;
}
else {
if ( today.getDay() < thisMonthsMeeting.getDay() ){
// it hasn't happened this month yet
meetingDate = thisMonthsMeeting;
} else {
//this month's meeting day has already passed
if( today.getMonth() == 11 ){
// rolling over to the next year
meetingDate = getSecondTuesdayInMonth(0, today.getYear() + 1);
} else {
meetingDate = getSecondTuesdayInMonth(today.getMonth() + 1, today.getYear());
}
}
}
return meetingDate;
}
// this is a helper function to get the second tuesday in any month
// returns a Date() object
function getSecondTuesdayInMonth(var month, var year){
var saturdays = 0;
var testDay= new Date();
while( testDay.getDay() != 2 && saturdays < 2 ){
//while the day we are testing isnt tuesday (2) and we haven't found it twice
if( testDay.getDay() == 2 )
saturdays = saturdays + 1; //we found a saturday
testDay= new Date(testDay.getTime() + 86400000); //increment our day to the next day
}
//when we finish the while loop, we are on our day
return testDay;
}
So, I figure that the meat of your problem is: How do I know what the second saturday of each month is?
Not tested, but this is what I came up with:
It is abstracted for any nth day of any month.
nthDate = function(nth_week, nth_day, month){
var src_date = new Date();
src_date.setDate(1);
src_date.setMonth(month);
return ( (nth_week * 7) - src_date.getDay() ) - ( Math.abs( nth_day - 6) );
};
var cur_date = new Date();
var cur_day = cur_date.getDay();
//2 for the 2nd week of the month
//6 is the integer value for saturday (days of the week 0-6)
var nth_date = nthDate( 2, 6, cur_date.getMonth() );
if(cur_day < nth_date){
//display the upcoming date here
}else if( cur_day > nth_date){
//figure out next month's date and display that
var next_date = nthDate(2, 6, (cur_date.getMonth() +1) );
//does this deal with the case of the month being december?? not sure.
}
The 2nd week is in the range of 14 days into the month.
We can:
first subtract the offset for the day of the week that this month starts with,
then second:
we can subtract the offset for the day of the week that we are looking for.
(this needs to be the offset of days, so saturday is a 0 (zero) offset. We get this value from the absolute value of nth day minus the number of days in the week.
This gives us the date of the second saturday.
Then, because you have some ints you can do a simple compare against the values.
If we're before the second saturday, display that, if not calculate a new date for next month.
Hope that helps.
given a date object,how to get previous week's first day
This Datejs library looks like it can do that sort of thing relatively easily.
Code:
function getPreviousSunday()
{
var today=new Date();
return new Date().setDate(today.getDate()-today.getDay()-7);
}
function getPreviousMonday()
{
var today=new Date();
if(today.getDay() != 0)
return new Date().setDate(today.getDate()-7-6);
else
return new Date().setDate(today.getDate()-today.getDay()-6);
}
Reasoning:
Depends what you mean by previous week's first day. I'll assume you mean previous sunday for the sake of this discussion.
To find the number of days to subtract:
Get the current day of the week.
If the current day of the week is Sunday you subtract 7 days
If the current day is Monday you subtract 8 days
...
If the current day is Saturday 13 days
The actual code once you determine the number of days to subtract is easy:
var previous_first_day_of_week=new Date().setDate(today.getDate()-X);
Where X is the above discussed value. This value is today.getDay() + 7
If by first day of the week you meant something else, you should be able to deduce the answer from the above steps.
Note: It is valid to pass negative values to the setDate function and it will work correctly.
For the code about Monday. You have that special case because getDay() orders Sunday before Monday. So we are basically replacing getDay() in that case with a value of getDay()'s saturday value + 1 to re-order sunday to the end of the week.
We use the value of 6 for subtraction with Monday because getDay() is returning 1 higher for each day than we want.
function previousWeekSunday(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 7);
}
function previousWeekMonday(d) {
if(!d.getDay())
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 13);
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 6);
}
I didn't quite understand other people's posts. Here is the javascript I use to display a Sun-Sat week relative to a given day. So, for instance, to get "last week," you're checking what the Sun/Sat goalposts were relative to seven days ago: new Date()-7
// variables
var comparedate = new Date()-7; // a week ago
var dayofweek = comparedate.getDay();
// just for declaration
var lastdate;
var firstadate;
// functions
function formatDate (dateinput) // makes date "mm/dd/yyyy" string
{
var month = dateinput.getMonth()+1;
if( month < 10 ) { month = '0' + month }
var date = dateinput.getDate();
if( date < 10 ) { var date = '0' + date }
var dateoutput = month + '/' + date + '/' + dateinput.getFullYear();
return dateoutput;
}
// Sunday to Saturday ... Sunday is the firstdate, Saturday is the lastdate
// (modify this block if you want something different eg: Monday to Sunday)
if ( dayofweek == 6 ) { lastdate = comparedate; firstdate = comparedate-6; } // Saturday
else if ( dayofweek == 0 ) { lastdate = comparedate+6; firstdate = comparedate; } // Sunday
else if ( dayofweek == 1 ) { lastdate = comparedate+5; firstdate = comparedate-1; } // Monday
else if ( dayofweek == 2 ) { lastdate = comparedate+4; firstdate = comparedate-2; } // Tuesday
else if ( dayofweek == 3 ) { lastdate = comparedate+3; firstdate = comparedate-3; } // Wednesday
else if ( dayofweek == 4 ) { lastdate = comparedate+2; firstdate = comparedate-4; } // Thursday
else if ( dayofweek == 5 ) { lastdate = comparedate+1; firstdate = comparedate-5; } // Friday
// Finish
var outputtowebpage = formatDate(firstdate) + ' - ' + formatDate(lastdate);
document.write(outputtowebpage);
I have to look this up every time I need to do it. So, I hope this is helpful to others.
First day of week can be either Sunday or Monday depending on what country you are in:
function getPrevSunday(a) {
return new Date(a.getTime() - ( (7+a.getDay())*24*60*60*1000 ));
};
function getPrevMonday(a) {
return new Date(a.getTime() - ( (6+(a.getDay()||7))*24*60*60*1000 ));
};
If you want to set a dateobject to the previous sunday you can use:
a.setDate(a.getDate()-7-a.getDay());
and for the previous monday:
a.setDate(a.getDate()-6-(a.getDay()||7));
In the other examples you will have a problem when sunday falls in other month. This should solve the problem:
var today, todayNumber, previousWeek, week, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
previousWeek = -1; //For every week you want to go back the past fill in a lower number.
week = previousWeek * 7;
mondayNumber = 1 - todayNumber + week;
monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+mondayNumber);