Javascript Date for the Second Monday of the month - javascript

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 />");

Related

Get the past week 7 day period from a given date in Javascript

I am trying to get the date range of the past Wednesday to past Tuesday(7 days) from today's date.
Say the current date is 2022-05-01(May 1st), I am expecting the result to be the past Tuesday(end date) to Past Wednesday (start date = Past Tuesday -7 days)
i.e 20 April 2022 to 26 April 2022
function getStartAndEndDates () {
var now = new Date('2022-05-01'); //May 1st 2022
var day = now.getDay();
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
var PastTuesday = new Date();
var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
console.log('End date is', PastTuesday.toISOString());
PastWednesday.setDate(PastTuesday.getDate() - 6);
console.log('Start Date is',PastWednesday.toISOString());
return[PastWednesday,PastTuesday];
}
Output obtained is:
End date is 2022-03-27T19:25:35.726Z //here month is set to March
Start Date is 2022-03-21T19:25:35.726Z
Expected Result is
End date is 2022-04-26T19:25:35.726Z // month is supposed to be April
Start Date is 2022-04-20T19:25:35.726Z
How can I change the code to get the expected result?
You should do something like
function getLastWeek(date) {
var today = new Date(date);
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
// Your DATE
date = '2022-05-01'
//
var lastWeek = getLastWeek(date);
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
console.log(lastWeekDisplay);
In your code:
var now = new Date('2022-05-01'); //May 1st 2022
Dates in the format YYYY-MM-DD are parsed as UTC, so the above will create a date object representing 2022-05-01T00:00:00Z.
var day = now.getDay();
This will return the local day number. For users with a zero or positive offset, it will return 0 (Sunday) but for users with a negative offset, it will return 6 (Saturday) because their local date is still the previous day.
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
Given day is 0 (for me), the above sets diff to 5.
var PastTuesday = new Date();
This creates a date for "now", which for me is 17 April.
var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
In the above, now.getDate returns 1, and 1 - 5 is -4, so it sets the date for PastTuesday to -4. Now PastTuesday is in April, so it is set to 4 days prior to the start of April, i.e. 27 March.
Note that this adjusts PastTuesday and creates a copy for PastWednesday at the same time.
console.log('End date is', PastTuesday.toISOString());
Shows the equivalent UTC date and time, with the time representing the time that the code was run.
PastWednesday.setDate(PastTuesday.getDate() - 6);
Sets PastWednesday to 6 days prior to PastTuesday.
Anyhow, what is required is to do everything either as UTC or local, don't mix the two.
Sticking to code as closely as possible to the original and assuming a timestamp in YYYY-MM-DD format is parsed to the function, consider the following, which does everything as local:
// Parse timestamp in YYYY-MM-DD format as local
function parseISOLocal(s = new Date().toLocaleDateString('en-CA')) {
let [y, m, d] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get week Wed to Tue prior to passed date
function getStartAndEndDates (date) {
// Parse timestamp as local
var pastTuesday = parseISOLocal(date);
// Adjust pastTuesday to previous Tuesday
var day = pastTuesday.getDay();
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
var pastWednesday = new Date(pastTuesday.setDate(pastTuesday.getDate() - diff));
console.log('End date is', pastTuesday.toDateString());
// Adjust pastWednesday to previous Wednesday
pastWednesday.setDate(pastTuesday.getDate() - 6);
console.log('Start Date is',pastWednesday.toDateString());
return [pastWednesday, pastTuesday];
}
// Sunday 1 May 2022
console.log(getStartAndEndDates('2022-05-01').map(d => d.toDateString()));
// Current date
console.log(getStartAndEndDates().map(d => d.toDateString()));

How to check if last day of month is on friday Javascript

I'm supposed to write a code for codewars to find out the number of times a month ends with a Friday within a range of years.
To start off, I did research and found out several solutions but I still couldn't figure out the results in the console.log.
The first solution is from this tutorial:
In this code, the solution is
let LastDay = new Date(1998, 5 + 1, 0).getDate();
I was able to get the date, but it wasn't clear which day the date falls upon.
Then I found another solution at w3schools. This solution also set the date to be the last day of this month:
var d = new Date();
d.setMonth(d.getMonth() +1, 0);
document.getElementById("demo").innerHTML = d;
However, it works if it displays it as innerHTML = Sat Nov 30 2019 00:57:09 GMT-0500 (Eastern Standard Time). However, when I tried to rewrite the code and console.log it like in this example:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(lastday);
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting. I thought that if it does display the dates, starting with the day, I can convert the date to string or array and check if the first element is Friday and then add it to the counter in the code I'm writing. How do I get the code to display the way I want it to.
something like this will work...
function LastDayOfMonth(Year, Month) {
return new Date((new Date(Year, Month, 1)) - 1);
}
var d = LastDayOfMonth(new Date().getYear(), new Date().getMonth())
//var d = LastDayOfMonth(2009, 11)
var dayName = d.toString().split(' ')[0];
console.log(dayName)
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting
Because you console.log the output of the setMonth method, not the date object:
let lastday = d.setMonth(month, 0);
console.log(lastday);
According to the documentation, the setMonth method returns:
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Instead you should use that output to create a new instance of the date object:
let lastday = new Date(d.setMonth(month, 0));
console.log(lastday);
Algorithms to get the last day of the month are generally based on setting a date to day 0 of the following month, which ends up being the last day of the required month.
E.g. to get the last day for June, 2019 (noting that 6 is July, not June):
let endOfJune = new Date(2019, 6, 0):
Once you have the date, you can get the day where 0 is Sunday, 1 is Monday, etc. and 5 is Friday:
let endOfJuneDay = endOfJune.getDay();
The set* methods modify the Date they're called on and return the time value for the modified date. So you don't need to assign the result to anything:
let d = new Date();
let month = d.getMonth() + 1;
// Set date to the new month
d.setMonth(month, 0);
console.log(d);
So if you want to loop over the months for a range of years and get the number that end with a Friday (or any particular day), you might loop over the months something like:
/*
** #param {number} startYear - start year of range
** #param {number} endYear - end year of range
** #param {number} dat - day number, 0 = Sunday, 1 = Monday, etc.
** default is 0 (Sunday)
*/
function countEOMDay(startYear, endYear, day = 0) {
// startYear must be <= end year
if (startYear > endYear) return;
// Start on 31 Jan of start year
let start = new Date(startYear, 0, 31);
// End on 31 Dec of end year
let end = new Date(endYear, 11, 31);
let count = 0;
// Loop over months from start to end
while (start <= end) {
// Count matching days
if (start.getDay() == day) {
++count;
}
// Increment month to end of next month
start.setMonth(start.getMonth() + 2, 0);
}
return count;
}
console.log(countEOMDay(2019, 2019, 5)); // 1
console.log(countEOMDay(2018, 2019, 5)); // 3
You can use setMonth() method to set the month of a date object. The return value of setMonth() method is milliseconds between the date object and midnight January 1 1970. That's what you get from console.log(lastday);
Your return value,
1575093343211
is milliseconds between your date object (d) and midnight January 1 1970.
If you want to get the expected date, you have to console log your date object instead the lastday, as follows:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(d);
output: Sat Nov 30 2019 00:02:47 GMT+0530 (India Standard Time)
This is an alternative solution I wrote to solve your problem. This will return the number of times a month ends with a Friday within a range of years. Hope this will help you :)
var days = [];
var count = 0;
function getLastFridaysCount(startYear, endYear) {
for (var year = startYear; year <= endYear; year++) {
days = [
31,
0 === year % 4 && 0 !== year % 100 || 0 === year % 400 ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
];
for (var month = 0; month <= 11; month++) {
var myDate = new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(days[month]);
if(myDate.getDay() == 5)
{
count++;
}
}
}
return count;
}
console.log("count", getLastFridaysCount(2014, 2017));
this is the solution, in the code can find the comments "//" explaining of what happens in each iteration.
function lastDayIsFriday(initialYear, endYear) {
let count = 0;
//according to when the year ends starts the loop
if (endYear !== undefined) {
let start = new Date(initialYear, 0, 31);
let end = new Date(endYear, 11, 31);
while(start <= end) { //check if the start date is < or = to the end
//The getDay() method returns the day of the week (from 0 to 6) for the specified date.
if(start.getDay() === 5) { //if = to FriYAY!!!
count++; //count the day
}
start.setMonth(start.getMonth()+2, 0);// returns the month (from 0 to 11) .getMonth
} //& sets the month of a date object .setMonth
return count;
} else {
let start = new Date(initialYear, 0, 31);
console.log(start.toString());
for(let i = 0; i < 12; i++) {
if(start.getDay() === 5) {
count++;
}
start.setMonth(start.getMonth() + 2, 0);
// console.log(start.toString());
}
return count;
}
}

Get a given weekday in a given month with JavaScript

I'm trying to get the nth weekday—for example, the second Sunday—of a month in which a certain date falls.
For instance, if the date is August 24, 2015, I'd like to do this:
nthDayOfMonth(0, 2, new Date(2015, 7, 24))
and get August 9, 2015 (2nd Sunday in August). I'd then like to be able to add a month to the date, call the function again, and get September 13, 2015 (2nd Sunday in September).
For some reason the below code is not working.
What am I missing?
function nthDayOfMonth(day, n, date) {
console.log(day);
console.log(n);
var count = 0;
var idate = new Date(date);
idate.setDate(1);
while ((count) < n) {
idate.setDate(idate.getDate() + 1);
if (idate.getDay() == day) {
count++;
}
}
return idate;
}
You have to check idate.getDay() before incrementing the day of the month. Otherwise you'll get an incorrect answer if the desired weekday falls on the first of the month.
The following snippet demonstrates the corrected function.
function print(s) {
document.write(s + '<br />');
}
function nthWeekdayOfMonth(weekday, n, date) {
var count = 0,
idate = new Date(date.getFullYear(), date.getMonth(), 1);
while (true) {
if (idate.getDay() === weekday) {
if (++count == n) {
break;
}
}
idate.setDate(idate.getDate() + 1);
}
return idate;
}
// Second Sunday of the current month.
var date = new Date();
print(date = nthWeekdayOfMonth(0, 2, date));
// Second Sunday of next month.
date.setMonth(date.getMonth() + 1);
print(date = nthWeekdayOfMonth(0, 2, date));
// First Tuesday of September 2015.
print(nthWeekdayOfMonth(2, 1, new Date(2015, 8)));
// First Wednesday of September 2015.
print(nthWeekdayOfMonth(3, 1, new Date(2015, 8)));
// Second Tuesday of September 2015.
print(nthWeekdayOfMonth(2, 2, new Date(2015, 8)));
// Second Wednesday of September 2015.
print(nthWeekdayOfMonth(3, 2, new Date(2015, 8)));
body {
font-family: sans-serif;
}
There's an even better approach that calculates the desired date without looping. We start by considering the weekday of the first day of the month. Suppose it's a Saturday, which JavaScript calls 6, and you're looking for a Sunday, which is 0.
To get to the first Sunday of the month, you have to advance the date by this number of days:
0 - 6 + 7
The result is 1. How does the calculation work? 0 - 6 is the number of days from weekday 6 to weekday 0, and to turn a negative value into a valid weekday, we add 7.
In general, the number of days from weekday a to weekday b is
(b - a + 7) % 7
To continue the example, suppose that we wanted the first Sunday of the month. In that case, we've arrived. But if we want the second day of the month, we have to advance the date by 7 more days. In general, given n such that n == 1 means the first occurrence of a given weekday, we have to advance by (n - 1) * 7 days.
To put it all together, if date is the first day of the month, we can get to the nth occurrence of weekday by advancing
(weekday - date.getDay() + 7) % 7 + (n - 1) * 7
days past the first day of the month.
This approach is implemented below.
function print(s) {
document.write(s + '<br />');
}
function nthWeekdayOfMonth(weekday, n, date) {
var date = new Date(date.getFullYear(), date.getMonth(), 1),
add = (weekday - date.getDay() + 7) % 7 + (n - 1) * 7;
date.setDate(1 + add);
return date;
}
// Second Sunday of the current month.
var date = new Date();
print(date = nthWeekdayOfMonth(0, 2, date));
// Second Sunday of next month.
date.setMonth(date.getMonth() + 1);
print(date = nthWeekdayOfMonth(0, 2, date));
// First Tuesday of September 2015.
print(nthWeekdayOfMonth(2, 1, new Date(2015, 8)));
// First Wednesday of September 2015.
print(nthWeekdayOfMonth(3, 1, new Date(2015, 8)));
// Second Tuesday of September 2015.
print(nthWeekdayOfMonth(2, 2, new Date(2015, 8)));
// Second Wednesday of September 2015.
print(nthWeekdayOfMonth(3, 2, new Date(2015, 8)));
body {
font-family: sans-serif;
}
Your code seems to work fine. To add a month, you can use d.setMonth(d.getMonth()+1).
Try this demo:
function nthDayOfMonth(day, n, date) {
var count = 0,
idate = new Date(date);
idate.setDate(1);
while (count < n) {
idate.setDate(idate.getDate() + 1);
if (idate.getDay() == day) { count++; }
}
return idate;
}
// Today : 2015-08-24
var today = new Date();
// Second Sunday of current month : 2015-08-09
var res = nthDayOfMonth(0, 2, today);
// res plus 1 month : 2015-09-09 (Wednesday)
var plusOne = new Date( res );
plusOne.setMonth(plusOne.getMonth() + 1);
// Second Sunday of next month : 2015-09-13
var res2 = nthDayOfMonth(0, 2, plusOne);
document.body.innerHTML = 'Today is <br>' + today + '<br>'
+ 'Second Sunday of current month is <br>' + res + '<br>'
+ 'If you add a month to it, you get <br>' + plusOne + '<br>'
+ 'And second Sunday of that month is <br>' + res2;
I just added a tweak to Michael Laszlo's excellent answer to allow the caller to provide n==5 (or any larger value) to indicate that the last weekday of the month is desired:
function nthWeekdayOfMonth(weekday, n, date) {
var month = date.getMonth();
var date = new Date(date.getFullYear(), month, 1),
add = (weekday - date.getDay() + 7) % 7 + (n - 1) * 7;
// make sure that we stay in the same month
do {
date.setMonth(month);
date.setDate(1 + add);
add -= 7;
} while (date.getMonth() != month);
return date;
}

Using Javascript to automatically adjust date to 2nd Saturday of every month?

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.

How do I get the first day of the previous week from a date object in JavaScript?

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);

Categories