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.
Related
This question already has answers here:
Find day difference between two dates (excluding weekend days)
(13 answers)
Closed 3 years ago.
In my application i have two date picker as start date and end date. when user choose start and end date the system will show the days between two dates but excluding the saturday and sunday. How to calculate it by using angularjs?
Does something like this work:
var startDate = new Date("01-10-2020");
var endDate = new Date("01-20-2020");
var nextDay = new Date(startDate);
var cnt = 0;
do {
/*if (nextDay.getDay() >= 1 && nextDay.getDay() <= 5) {
cnt = cnt + 1;
}*/
cnt += (nextDay.getDay() >= 1 && nextDay.getDay() <= 5) ? 1 : 0;
nextDay.setDate(nextDay.getDate() + 1);
} while (nextDay <= endDate);
console.log("Number of week days between " + startDate + " and " + endDate + " = " + cnt);
Here is the fiddler.
You don't want to do an expensive loop over every day to see whether it is Saturday or Sunday. The logic should be as follows:
Work in UTC so we don't need to worry about time zone
Calculate total number of calendar weeks. In a single calendar week, there are guaranteed to be 5 weekdays (not weekends == SAT || SUN)
Calculate the remainder of days. This will be added to the calculation later.
Determine the "finalAdjustment" by seeing if the remainder falls on weekend days.
The number of weekdays is (5 * numWeeks) + remainderDays + finalAdjust
(function() {
"use strict";
var SUN = 0;
var MON = 1;
var TUE = 2;
var WED = 3;
var THU = 4;
var FRI = 5;
var SAT = 6;
function isWeekendDay(day) {
return day === SAT || day === SUN;
}
function numberWeekDays(start, end) {
var numCalendarDays = (end - start) / 1000 / 60 / 60 / 24;
var numWeeks = Math.floor(numCalendarDays / 7);
// Potential days to add on to the number of full calendar
// weeks. This will be adjusted by "finalAdjust"
var remainderDays = numCalendarDays % 7;
// Adjustments for start and end dates being on a weekend
// ----------------------------
// Start at one because the same day should count as 1
// but number of days between same day is 0 based on
// arithmetic above.
// Change this to 0 if you don't want end date inclusive...
var finalAdjust = 1;
var startDay = start.getUTCDay();
var endDay = end.getUTCDay();
// On a weekend, so adjust by subtracting 1
if (isWeekendDay(startDay)) {
finalAdjust--;
}
// On a weekend, so adjust by subtracting 1
if (isWeekendDay(endDay)) {
finalAdjust--;
}
// This accounts for subtracting an extra weekend when starting
// at the beginning of a weekend (e.g. Saturday into Monday)
// The end day cannot also be on a weekend based on week modular division (mod 7)
if (startDay === SAT && remainderDays > 2) {
finalAdjust--;
}
// ---------------------------
// For every full calendar week there are 5 week days
// Use that number with the remainderDays and finalAdjust above
// to arrive at the answer.
var numWeekDays = (5 * numWeeks) + remainderDays + finalAdjust;
return numWeekDays;
}
// Test cases
// Assume that the start and end dates are inclusive
// 2020-01-01 to 2020-01-01 is one day
// 2020-01-01 to 2020-01-02 is two days
// ----------------------
// A Wednesdday
var start = new Date("2020-01-08");
// A Saturday
var end = new Date("2020-02-01");
// Expected answer: 18
console.log(numberWeekDays(start, end));
// A Saturday
start = new Date("2020-01-05");
// A Monday
end = new Date("2020-01-31");
// Expected answer: 20
console.log(numberWeekDays(start, end));
// Weekday to weekday Tuesday to
start = new Date("2020-01-07");
end = new Date("2020-01-16");
// Expected: 8
console.log(numberWeekDays(start, end));
// Same week: Mon-Wed
start = new Date("2020-01-06");
end = new Date("2020-01-08");
// Expected answer: 3
console.log(numberWeekDays(start, end));
// Same day
start = new Date("2020-01-08");
end = new Date("2020-01-08");
// Expect: 1
console.log(numberWeekDays(start, end));
// Weekend only
start = new Date("2020-01-04");
end = new Date("2020-01-05");
// Expect: 0;
console.log(numberWeekDays(start, end));
// ------------------
}());
As others have stated, a date library like moment is useful here because it gives you a lot of utility functions for working with dates and durations.
Objective: Automatically display the date of an upcoming bi-weekly event. In this case, every Saturday. Ideally by modifying existing code.
e.g. If there is an event July 9, and today is July 11, the next event will be July 23. If today is July 24th, next event is Aug 6, and so on...
Problem: How to calculate it's date? (I assume a reference starting date will be needed, e.g. July 9, 2016)
Background / Existing code: Calculate the date of a nearest given day of the week. (e.g. if today is Monday the 14th, whats the date of the upcoming Saturday?). NOTE: In this case, the event is every Friday & Saturday. We display the dates for upcoming Friday and Saturday. BUT I wanted to make sure the dates displayed always fell on the same weekend. (If today is Saturday, FRI date should be yesterday, and SAT date should be today).
(function() {
// Today's date
var startingDate = new Date();
// Find date of nearest day of week
function dateOfNearestDay(startingDate, nearestDay) {
// Date object to work with inside the function
var nearestTime = new Date(startingDate.getTime());
// If today is Sat, use last Fri's date, else calculate date of nearest day
if (startingDate.getDay() === 6 && nearestDay === 5) {
nearestTime.setDate((startingDate.getDate() + (7 + nearestDay - startingDate.getDay()) % 7) - 7);
}
else {
nearestTime.setDate(startingDate.getDate() + (7 + nearestDay - startingDate.getDay()) % 7);
}
return nearestTime;
}
// Format date as needed for display
function getMonthAndDay(date) {
// Array to store month names for translation
monthNames = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.'];
return monthNames[date.getMonth()]+ " " + date.getDate();
}
// Get date object of nearest Friday and Saturday
var friday = dateOfNearestDay(startingDate, 5);
var saturday = dateOfNearestDay(startingDate, 6);
var fridayDate = document.getElementById('friday');
var saturdayDate = document.getElementById('saturday');
// Write month & day of nearest day
fridayDate.textContent = getMonthAndDay(friday);
saturdayDate.textContent = getMonthAndDay(saturday);
}());
The function nextEvent for a given date today and known date of the event computes the next bi-weekly recurring event after today or today:
// Today's date
var startingDate = new Date();
startingDate.setDate(startingDate.getDate());
// Find date of nearest day of week
function dateOfNearestDay(startingDate, nearestDay) {
// Date object to work with inside the function
var nearestTime = new Date(startingDate.getTime());
// If today is Sat, use last Fri's date, else calculate date of nearest day
if (startingDate.getDay() === 6 && nearestDay === 5) {
nearestTime.setDate((startingDate.getDate() + (7 + nearestDay - startingDate.getDay()) % 7) - 7 - 7);
} else {
nearestTime.setDate(startingDate.getDate() + (7 + nearestDay - startingDate.getDay()) % 7 - 7);
}
return nearestTime;
}
// For a given today and last event finds closest next event from today.
// Assumption is that event is recurring every 14 days
function nextEvent(today, event) {
var eventRecurrence = 14; // recurrence of the event in days
var nextEventTime = new Date(today.getTime());
nextEventTime.setDate(today.getDate() + ((today.getDate() > event.getDate()) ? eventRecurrence : 0) - (today.getDate() - event.getDate()) % eventRecurrence);
return nextEventTime;
}
// Format date as needed for display
function getMonthAndDay(date) {
// Array to store month names for translation
monthNames = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.'];
return monthNames[date.getMonth()] + " " + date.getDate();
}
// Get date object of nearest Friday and Saturday
var friday = dateOfNearestDay(startingDate, 5);
var saturday = dateOfNearestDay(startingDate, 6);
var nextFridayEvent = nextEvent(startingDate, friday);
var nextSaturdayEvent = nextEvent(startingDate, saturday);
// Write months & days of the variables
console.log('Today is ' + getMonthAndDay(startingDate));
console.log('Friday Event ' + getMonthAndDay(friday));
console.log('Saturday Event ' + getMonthAndDay(saturday));
console.log('Next Friday Event ' + getMonthAndDay(nextFridayEvent));
console.log('Next Saturday Event ' + getMonthAndDay(nextSaturdayEvent))
I have modified your function dateOfNearestDay with 2x-7 in order to demonstrate events before today.
I am working with a group that meets the second monday of the month and they want their site to reflect the NEXT meeting date. I have the script to show this months second monday, but i am having trouble with the if else statement. I need it to reflect the next upcoming event and not just this months date. IE. this months event date was Aug 13 2012 which is past the current date (aug 21 2012). I would like it to move to the next available date Sept 10 2012. Below is the code i have so far.
<script type="text/javascript">
Date.prototype.x = function () {
var d = new Date (this.getFullYear(), this.getMonth(), 1, 0, 0, 0)
d.setDate (d.getDate() + 15 - d.getDay())
return d
}
Date.prototype.getSecondMonday = function () {
var d = new Date (this.getFullYear(), 1, 1, 0, 0, 0)
d.setMonth(this.getMonth()+1)
d.setDate (d.getDate() + 15 - d.getDay())
return d
}
var today = new Date()
var todayDate = today.toDateString()
if (Date.prototype.x>todayDate)
{
document.write (new Date().x().toDateString());
}
else
{
document.write (new Date().getSecondMonday().toDateString());
}
</script>
If the date of the second Monday of the current month is less than the current date,
call the function on the first of the next month.
Date.prototype.nextSecondMonday= function(){
var temp= new Date(this), d= temp.getDate(), n= 1;
while(temp.getDay()!= 1) temp.setDate(++n);
temp.setDate(n+7);
if(d>temp.getDate()){
temp.setMonth(temp.getMonth()+1, 1);
return temp.nextSecondMonday();
}
return temp.toLocaleDateString();
}
/* tests
var x= new Date(2012, 7, 22);
x.nextSecondMonday()
Monday, September 10, 2012
var x= new Date(2012, 7, 12);
x.nextSecondMonday()
Monday, August 13, 2012
*/
You're missing () for the x function, so it's not executing it. :) Should be:
if (Date.prototype.x() > todayDate)
UPDATE:
Here is a fixed/working version of the logic cleaned up (and probably overly commented, but I guess it's at least there if anyone needs it).
Date.prototype.nextSecondMonday = function (){
// Load the month.
var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
var today = new Date();
// Check to see if the 1st is on a Monday.
var isMonday = (target.getDay() == 1);
// Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Monday.
// i.e. If the 1st is a Thursday, we would move back three days.
var targetDate = 15 - (target.getDay() - 1);
// Quick adjustment if the 1st is a Monday.
if (isMonday) targetDate -= 7;
// Move to the second Monday in the month.
target.setDate(targetDate);
// Second Monday is before today's date, so find the second Monday next month.
if (today > target) {
//return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
target.setMonth(target.getMonth() + 1);
return target.nextSecondMonday();
}
// Format and return string date of second Monday.
return target.toLocaleDateString();
}
// Working test for the year 2012.
//for (var i = 0; i < 12; i++)
//$("#log").append(new Date(2012, i).nextSecondMonday() + "<br /><br />");
I have some friends' birthdays and want to separate them as follows :
birthdays which fall within the current week (within remaining days of current week starting from current day).
birthdays which fall within the current month (within remaining days of current month starting from current day).
birthdays which fall within the next month.
So all I want to know how to test each date in javascript to see if it falls within the remaining days of the current week/current month/next month.
N.B: say I have those dates in m/d/Y(06/29/1990) format.
Thanks
Convert your date and current time to Date object and use it for comparison. Some dry coding:
var now = new Date()
if (
(check.getFullYear() == now.getFullYear()) &&
(check.getMonth() == now.getMonth()) &&
(check.getDate() >= now.getDate())
) {
// remanining days in current month and today. Use > if you don't need today.
}
var nextMonth = now.getMonth() + 1
var nextYear = now.getFullYear()
if (nextMonth == 12) {
nextMonth = 0
nextYear++
}
if (
(check.getFullYear() == nextYear) &&
(check.getMonth() == nextMonth)
) {
// any day in next month. Doesn't include current month remaining days.
}
var now = new Date()
now.setHours(12)
now.setMinutes(0)
now.setSeconds(0)
now.setMilliseconds(0)
var end_of_week = new Date(now.getTime() + (6 - now.getDay()) * 24*60*60*1000 )
end_of_week.setHours(23)
end_of_week.setMinutes(59)
end_of_week.setSeconds(59) // gee, bye-bye leap second
if ( check >=now && check <= end_of_week) {
// between now and end of week
}
the code Using the Parse Date is
var selecteddate = '07/29/1990';
var datestr = selecteddate.split('/');
var month = datestr[0];
var day = datestr[1];
var year = datestr[2];
var currentdate = new Date();
var cur_month = currentdate.getMonth() + 1;
var cur_day =currentdate.getDate();
var cur_year =currentdate.getFullYear();
if(cur_month==month && day >= cur_day)
{
alert("in this month");
}
else
{
alert("not in this month");
}
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);