Javascript: get Monday and Sunday of the previous week - javascript

I am using the following script to get Monday (first) and Sunday (last) for the previous week:
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay() - 6; // Gets day of the month (e.g. 21) - the day of the week (e.g. wednesday = 3) = Sunday (18th) - 6
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first));
var endDate = new Date(curr.setDate(last));
This works fine if last Monday and Sunday were also in the same month, but I just noticed today that it doesn't work if today is December and last Monday was in November.
I'm a total JS novice, is there another way to get these dates?

You can get the previous Monday by getting the Monday of this week and subtracting 7 days. The Sunday will be one day before that, so:
var d = new Date();
// set to Monday of this week
d.setDate(d.getDate() - (d.getDay() + 6) % 7);
// set to previous Monday
d.setDate(d.getDate() - 7);
// create new date of day before
var sunday = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 1);
For 2012-12-03 I get:
Mon 26 Nov 2012
Sun 25 Nov 2012
Is that what you want?
// Or new date for the following Sunday
var sunday = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 6);
which gives
Sun 02 Dec 2012
In general, you can manipulate date objects by add and subtracting years, months and days. The object will handle negative values automatically, e.g.
var d = new Date(2012,11,0)
Will create a date for 2012-11-30 (noting that months are zero based so 11 is December). Also:
d.setMonth(d.getMonth() - 1); // 2012-10-30
d.setDate(d.getDate() - 30); // 2012-09-30

if you dont want to do it with an external library you should work with timestamps. i created a solution where you would substract 60*60*24*7*1000 (which is 604800000, which is 1 week in milliseconds) from the current Date and go from there:
var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
, day = beforeOneWeek.getDay()
, diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
, lastMonday = new Date(beforeOneWeek.setDate(diffToMonday))
, lastSunday = new Date(beforeOneWeek.setDate(diffToMonday + 6));

You could use a library like moment.js.
See the subtract method http://momentjs.com/docs/#/manipulating/subtract/

A few answers mentioned moment, but no one wrote about this simple method:
moment().day(-13) // Monday last week
moment().day(-7) // Sunday last week
.day sets a week day, so it doesn't matter what day is it today, only week matters.

This is the general solution of find any day of any week.
function getParticularDayTimestamp(lastWeekDay) {
var currentWeekMonday = new Date().getDate() - new Date().getDay() + 1;
return new Date().setDate(currentWeekMonday - lastWeekDay);
}
console.log(getParticularDayTimestamp(7)) // for last week monday
console.log(getParticularDayTimestamp(1)) // for last week sunday
console.log(getParticularDayTimestamp(14)) // for last to last week monday
console.log(getParticularDayTimestamp(8)) // for last to last week sunday

Using Moment you can do the following
var lastWeek = moment().isoWeek(moment().subtract(1,'w').week());
var mondayDifference = lastWeek.dayOfYear() - lastWeek.weekday() + 1;
var sundayDifference = mondayDifference - 1;
var lastMonday = moment().dayOfYear(mondayDifference);
var lastSunday = moment().dayOfYear(sundayDifference );

it can be this simple.
var today = new Date();
var sunday = new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate() - this.today.getDay());

Here you have a multi-purpose function:
function getThe(numOfWeeks, weekday, tense, fromDate) {
// for instance: var lastMonday = getThe(1,"Monday","before",new Date())
var targetWeekday = -1;
var dateAdjustment = clone(fromDate);
var result = clone(fromDate);
switch (weekday) {
case "Monday": targetWeekday = 8; break;
case "Tuesday": targetWeekday = 2; break;
case "Wednesday": targetWeekday = 3; break;
case "Thursday": targetWeekday = 4; break;
case "Friday": targetWeekday = 5; break;
case "Saturday": targetWeekday = 6; break;
case "Sunday": targetWeekday = 7;
}
var adjustment = 7 * (numOfWeeks - 1);
if (tense == "after") adjustment = -7 * numOfWeeks;
dateAdjustment.setDate(fromDate.getDate() - targetWeekday);
var weekday = dateAdjustment.getDay();
result.setDate(fromDate.getDate() - weekday - adjustment);
result.setHours(0,0,0,0);
return result;
}
You can find the "clone(obj)" function in the next post: https://stackoverflow.com/a/728694/6751764

You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
if you want to use JavaScript then use the below code
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay()+1; // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first));
startDate = ""+startDate.getFullYear()+"-"+ (startDate.getMonth() + 1) + "-" + startDate.getDate()
var endDate = new Date(curr.setDate(last));
endDate = "" + (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear();
alert(startDate+" , "+endDate)

Related

How to get Monday of a week as a number

I would like to get the first day of a week in a given year (assuming the week starts on a Monday).
Scenario: The year is 2016. It should return 4, because Monday the 4th of January 2016 is the first day of week 1 in 2016.
How would I do that? I want something like this:
var date = new Date();
var week = 1;
var year = 2016;
date.getMonday(week, year); // 4 (because 04/01/2016 is a Monday and is week number 1)
week = 5;
date.getMonday(week, year); // 30 (because 30/01/2016 is a Monday and is week number 5)
Thanks
You can use JavaScript's getDay() method to figure out which day of the week a date object refers to.
var output = document.getElementById('output');
var year = 2016;
var firstMonday = new Date(year, 0, 1); // year, month (zero-index), date
// starting at January 1st, increment the date until a Monday (`getDay() = 1`)
while(firstMonday.getDay() !== 1) {
firstMonday.setDate(firstMonday.getDate() + 1);
}
// output the date of the first Monday in January
output.value = firstMonday.getDate();
<textarea id="output"></textarea>
I've made a function to solve this... see bellow
function getDayInWeek(dayOfWeek, week, year){
dayOfWeek = dayOfWeek % 7; //ensure day of week
var baseDate = new Date(year, 0, 1); //get the first day
var firstDayOfWeek = baseDate.getDay(); //get the first week day
var inWeek = (week - 1) * 7; //get the days to start of week
var diff = firstDayOfWeek - dayOfWeek; //get the diff for day in that week
if(diff < 0) diff += 7;
baseDate.setDate(inWeek + diff);
return baseDate.getDate(); //get the month day
}
to use specify the week day
// 0 = sunday
// 1 = monday
// 2 = tuesday
// 3 = wednesday
// 4 = thursday
// 5 = friday
// 6 = saturday
var firstMonday = getDayInWeek(1, 1, 2016); // the monday in first week of 2016
var mondayOf5 = getDayInWeek(1, 5, 2016); // the monday in 5th week of 2016
To get ISO-8601 week, which will always be a Monday, see link:
Wikipedia
Calculate ISO 8601
function getISOWeek(week, year) {
var _date = new Date(year, 0, 1 + (week - 1) * 7);
var date_of_week = _date.getDay();
var ISOweekStart = _date;
(date_of_week <= 4) ? ISOweekStart.setDate(_date.getDate() - _date.getDay() + 1): ISOweekStart.setDate(_date.getDate() + 8 - _date.getDay());
return ISOweekStart;
}
console.log(getISOWeek(10, 2016));

How do I calculate the date in JavaScript three months prior to today?

I Am trying to form a date which is 3 months before the current date. I get the current month by the below code
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
Can you guys provide me the logic to calculate and form a date (an object of the Date data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?
var d = new Date();
d.setMonth(d.getMonth() - 3);
This works for January. Run this snippet:
var d = new Date("January 14, 2012");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() - 3);
console.log(d.toLocaleDateString());
There are some caveats...
A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.
Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:
It also says that one month is 30.4167 days long:
So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.
If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:
const d = new Date("March 31, 2019");
console.log(d.toLocaleDateString());
const month = d.getMonth();
d.setMonth(d.getMonth() - 1);
while (d.getMonth() === month) {
d.setDate(d.getDate() - 1);
}
console.log(d.toLocaleDateString());
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
I recommend using a library called Moment.js.
It is well tested, works cross browser and on server side(I am using it both in Angular and Node projects). It has great support for locale dates.
http://momentjs.com/
var threeMonthsAgo = moment().subtract(3, 'months');
console.log(threeMonthsAgo.format()); // 2015-10-13T09:37:35+02:00
.format() returns string representation of date formatted in ISO 8601 format. You can also use it with custom date format like this:.format('dddd, MMMM Do YYYY, h:mm:ss a')
A "one liner" (on many line for easy read)) to be put directly into a variable:
var oneMonthAgo = new Date(
new Date().getFullYear(),
new Date().getMonth() - 1,
new Date().getDate()
);
This should handle addition/subtraction, just put a negative value in to subtract and a positive value to add. This also solves the month crossover problem.
function monthAdd(date, month) {
var temp = date;
temp = new Date(date.getFullYear(), date.getMonth(), 1);
temp.setMonth(temp.getMonth() + (month + 1));
temp.setDate(temp.getDate() - 1);
if (date.getDate() < temp.getDate()) {
temp.setDate(date.getDate());
}
return temp;
}
To make things really simple you can use DateJS, a date library for JavaScript:
http://www.datejs.com/
Example code for you:
Date.today().add({ months: -1 });
If the setMonth method offered by gilly3 isn't what you're looking for, consider:
var someDate = new Date(); // add arguments as needed
someDate.setTime(someDate.getTime() - 3*28*24*60*60);
// assumes the definition of "one month" to be "four weeks".
Can be used for any amount of time, just set the right multiples.
I like the simplicity of gilly3's answer, but users will probably be surprised that a month before March 31 is March 3. I chose to implement a version that sticks to the end of the month, so a month before March 28, 29, 30, and 31 will all be Feb 28 when it's not a leap year.
function addMonths(date, months) {
var result = new Date(date),
expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12;
result.setMonth(result.getMonth() + months);
if (result.getMonth() !== expectedMonth) {
result.setDate(0);
}
return result;
}
var dt2004_05_31 = new Date("2004-05-31 0:00"),
dt2001_05_31 = new Date("2001-05-31 0:00"),
dt2001_03_31 = new Date("2001-03-31 0:00"),
dt2001_02_28 = new Date("2001-02-28 0:00"),
result = addMonths(dt2001_05_31, -2);
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2001_05_31, -3);
console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2001_05_31, 36);
console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString());
result = addMonths(dt2004_05_31, -38);
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());
console.log('Done.');
Do this
let currentdate = new Date();
let last3months = new Date(currentdate.setMonth(currentdate.getMonth()-3));
Javascript's setMonth method also takes care of the year. For instance, the above code will return 2020-01-29 if currentDate is set as new Date("2020-01-29")
For get date three monts prior to today :
let d = new Date(new Date().setMonth(new Date().getMonth() - 3))
console.log(d.toISOString().slice(0, 10))
// 2022-05-24 (today is 2022-08-24)
var d = new Date("2013/01/01");
console.log(d.toLocaleDateString());
d.setMonth(d.getMonth() + 18);
console.log(d.toLocaleDateString());
This is the Smallest and easiest code.
var minDate = new Date();
minDate.setMonth(minDate.getMonth() - 3);
Declare variable which has current date.
then just by using setMonth inbuilt function we can get 3 month back date.
There is an elegant answer already but I find that its hard to read so I made my own function. For my purposes I didn't need a negative result but it wouldn't be hard to modify.
var subtractMonths = function (date1,date2) {
if (date1-date2 <=0) {
return 0;
}
var monthCount = 0;
while (date1 > date2){
monthCount++;
date1.setMonth(date1.getMonth() -1);
}
return monthCount;
}
As I don't seem to see it already suggested....
const d = new Date();
const day = d.getDate();
const goBack = 3;
for (let i = 0; i < goBack; i++) d.setDate(0);
d.setDate(day);
This will give you the date of today's date 3 months ago as .setDate(0) sets the date to the last day of last month irrespective of how many days a month contains. day is used to restore today's date value.
var todayDate = new Date().toISOString().slice(0, 10);
var d = new Date(todayDate);
d.setMonth(d.getMonth() -3);
console.log(todayDate)
console.log(d.toISOString().slice(0, 10));
d.setMonth changed local time in browser try
const calcDate = (m) => {
let date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
let days = 0;
if (m > 0) {
for (let i = 1; i < m; i++) {
month += 1;
if (month > 12) {
year += 1;
month = 1;
}
days += new Date(year, month, 0).getDate();
}
} else {
for (let i = m; i < 0; i++) {
month -= 1;
if (month < 1) {
year -= 1;
month = 12;
}
days -= new Date(year, month, 0).getDate();
}
}
const newTime = date.getTime() + 3600 * 24 * 1000 * days;
return new Date(newTime);
};
calcDate(3)//+3 month
Since "Feb 31th" is auto converted to "March 3" or "March 2", as a month before "March 31th", which is quite counterintuitive, I decided to do it just like how I do it in my mind.
Similar to #Don Kirkby 's answer, I also revise the date with the last day of the target month.
function nMonthsAgo(date, n) {
// get the target year, month, date
const y = date.getFullYear() - Math.trunc(n / 12)
const m = date.getMonth() - n % 12
let d = date.getDate()
if (d > 27) { // get a valid date
const lastDateofMonth = new Date(y, m + 1, 0).getDate()
d = Math.min(d, lastDateofMonth)
}
return new Date(y, m, d)
}
d = new Date('2022-03-31')
nMonthsAgo(d, 1).toLocaleDateString()
Finally, I love what #gilly3 said in his answer:
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
for (let monthOfYear = 0; monthOfYear < 12; monthOfYear++) {
const maxDate = new Date();
const minDate = new Date();
const max = maxDate.setMonth(maxDate.getMonth() - (monthOfYear - 1), 0);
const min = maxDate.setMonth(minDate.getMonth() - (monthOfYear), 1);
console.log('max: ', new Date(max));
console.log('min: ', new Date(min));
}
In my case I needed to substract 1 month to current date. The important part was the month number, so it doesn't care in which day of the current month you are at, I needed last month. This is my code:
var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)
dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month
//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
Substract 1 month to actual date it's not accurate, that's why in first place I set first day of the month (first day of any month always is first day) and in second place I substract 1 day, which always send you to last month.
Hope to help you dude.
var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)
dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month
//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)
var date=document.getElementById("date");
var d = new Date();
document.write(d + "<br/>");
d.setMonth(d.getMonth() - 6);
document.write(d);
if(d<date)
document.write("lesser then 6 months");
else
document.write("greater then 6 months");
Pass a JS Date object and an integer of how many months you want to add/subtract. monthsToAdd can be positive or negative. Returns a JS date object.
If your originalDateObject is March 31, and you pass -1 as monthsToAdd, then your output date will be February 28.
If you pass a large number of months, say 36, it will handle the year adjustment properly as well.
const addMonthsToDate = (originalDateObject, monthsToAdd) => {
const originalDay = originalDateObject.getUTCDate();
const originalMonth = originalDateObject.getUTCMonth();
const originalYear = originalDateObject.getUTCFullYear();
const monthDayCountMap = {
"0": 31,
"1": 28,
"2": 31,
"3": 30,
"4": 31,
"5": 30,
"6": 31,
"7": 31,
"8": 30,
"9": 31,
"10": 30,
"11": 31
};
let newMonth;
if (newMonth > -1) {
newMonth = (((originalMonth + monthsToAdd) % 12)).toString();
} else {
const delta = (monthsToAdd * -1) % 12;
newMonth = originalMonth - delta < 0 ? (12+originalMonth) - delta : originalMonth - delta;
}
let newDay;
if (originalDay > monthDayCountMap[newMonth]) {
newDay = monthDayCountMap[newMonth].toString();
} else {
newDay = originalDay.toString();
}
newMonth = (+newMonth + 1).toString();
if (newMonth.length === 1) {
newMonth = '0' + newMonth;
}
if (newDay.length === 1) {
newDay = '0' + newDay;
}
if (monthsToAdd <= 0) {
monthsToAdd -= 11;
}
let newYear = (~~((originalMonth + monthsToAdd) / 12)) + originalYear;
let newTime = originalDateObject.toISOString().slice(10, 24);
const newDateISOString = `${newYear}-${newMonth}-${newDay}${newTime}`;
return new Date(newDateISOString);
};
Following code give me Just Previous Month From Current Month even the date is 31/30 of current date and last month is 30/29/28 days:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date after changing the month.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var d = new Date("March 29, 2017"); // Please Try the result also for "March 31, 2017" Or "March 30, 2017"
var OneMonthBefore =new Date(d);
OneMonthBefore.setMonth(d.getMonth(),0);
if(OneMonthBefore.getDate() < d.getDate() )
{
d.setMonth(d.getMonth(),0);
}else
{
d.setMonth(d.getMonth()-1);
}
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
var d = new Date();
document.write(d + "<br/>");
d.setMonth(d.getMonth() - 6);
document.write(d);

Show week number with Javascript?

I have the following code that is used to show the name of the current day, followed by a set phrase.
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array(
"It's Sunday, the weekend is nearly over",
"Yay! Another Monday",
"Hello Tuesday, at least you're not Monday",
"It's Wednesday. Halfway through the week already",
"It's Thursday.",
"It's Friday - Hurray for the weekend",
"Saturday Night Fever");
var now = new Date();
document.write(dayNames[now.getDay()] + ".");
// -->
</script>
What I would like to do is have the current week number in brackets after the phrase. I have found the following code:
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
Which was taken from http://javascript.about.com/library/blweekyear.htm but I have no idea how to add it to existing javascript code.
Simply add it to your current code, then call (new Date()).getWeek()
<script>
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
var weekNumber = (new Date()).getWeek();
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>
In case you already use jQuery-UI (specifically datepicker):
Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }
Usage:
var myDate = new Date();
myDate.getWeek();
More here: UI/Datepicker/iso8601Week
I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jQuery-UI this might just be a simple fit for someone - as it was for me.
If you don't use jQuery-UI and have no intention of adding the dependency. You could just copy their iso8601Week() implementation since it is written in pure JavaScript without complex dependencies:
// Determine the week of the year (local timezone) based on the ISO 8601 definition.
Date.prototype.iso8601Week = function () {
// Create a copy of the current date, we don't want to mutate the original
const date = new Date(this.getTime());
// Find Thursday of this week starting on Monday
date.setDate(date.getDate() + 4 - (date.getDay() || 7));
const thursday = date.getTime();
// Find January 1st
date.setMonth(0); // January
date.setDate(1); // 1st
const jan1st = date.getTime();
// Round the amount of days to compensate for daylight saving time
const days = Math.round((thursday - jan1st) / 86400000); // 1 day = 86400000 ms
return Math.floor(days / 7) + 1;
};
console.log(new Date().iso8601Week());
console.log(new Date("2020-01-01T00:00").iso8601Week());
console.log(new Date("2021-01-01T00:00").iso8601Week());
console.log(new Date("2022-01-01T00:00").iso8601Week());
console.log(new Date("2023-12-31T00:00").iso8601Week());
console.log(new Date("2024-12-31T00:00").iso8601Week());
Consider using my implementation of "Date.prototype.getWeek", think is more accurate than the others i have seen here :)
Date.prototype.getWeek = function(){
// We have to compare against the first monday of the year not the 01/01
// 60*60*24*1000 = 86400000
// 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01
var day_miliseconds = 86400000,
onejan = new Date(this.getFullYear(),0,1,0,0,0),
onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
days_for_next_monday = (8-onejan_day),
onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
// If one jan is not a monday, get the first monday of the year
first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
this_time = this_date.getTime(),
days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));
var first_monday_year = new Date(first_monday_year_time);
// We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
// then 7/7 = 1, and as we are 7 days from first monday,
// we should be in week number 2 instead of week number 1 (7/7=1)
// We consider week number as 52 when "days_from_first_monday" is lower than 0,
// that means the actual week started before the first monday so that means we are on the firsts
// days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
// so friday 01/01 is part of week number 52 from past year)
// "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong
return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}
You can check my public repo here https://bitbucket.org/agustinhaller/date.getweek (Tests included)
If you want something that works and is future-proof, use a library like MomentJS.
moment(date).week();
moment(date).isoWeek()
http://momentjs.com/docs/#/get-set/week/
It looks like this function I found at weeknumber.net is pretty accurate and easy to use.
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript
// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you're lucky like me and need to find the week number of the month a little adjust will do it:
// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you already use Angular, then you could profit $filter('date').
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
By adding the snippet you extend the Date object.
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
If you want to use this in multiple pages you can add this to a seperate js file which must be loaded first before your other scripts executes. With other scripts I mean the scripts which uses the getWeek() method.
All the proposed approaches may give wrong results because they don’t take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86’400’000 milliseconds, it is better to use an approach like the following one:
getDaysDiff = function (dateObject0, dateObject1) {
if (dateObject0 >= dateObject1) return 0;
var d = new Date(dateObject0.getTime());
var nd = 0;
while (d <= dateObject1) {
d.setDate(d.getDate() + 1);
nd++;
}
return nd-1;
};
I was coding in the dark (a challenge) and couldn't lookup, bring in any dependencies or test my code.
I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code instead.
var elm = document.createElement('input')
elm.type = 'week'
elm.valueAsDate = new Date()
var week = elm.value.split('W').pop()
console.log(week)
Just a proof of concept of how you can get the week in any other way
But still i recommend any other solution that isn't required by the DOM.
With that code you can simply;
document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");
(You will need to paste the getWeek function above your current script)
You could find this fiddle useful. Just finished.
https://jsfiddle.net/dnviti/ogpt920w/
Code below also:
/**
* Get the ISO week date week number
*/
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() != 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
}
/**
* Get the ISO week date year number
*/
Date.prototype.getWeekYear = function ()
{
// Create a new date object for the thursday of this week
var target = new Date(this.valueOf());
target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);
return target.getFullYear();
}
/**
* Convert ISO week number and year into date (first day of week)
*/
var getDateFromISOWeek = function(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
var printDate = function(){
/*var dateString = document.getElementById("date").value;
var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field
var dateInput = document.getElementById("date").value;
if (dateInput == ""){
var date = new Date(); // get today date object
}
else{
var date = new Date(dateInput); // get date from field
}
var day = ("0" + date.getDate()).slice(-2); // get today day
var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month
var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date
var year = date.getFullYear();
var week = ("0" + (date.getWeek())).slice(-2);
var locale= "it-it";
document.getElementById("date").value = fullDate; // set input field
document.getElementById("year").value = year;
document.getElementById("week").value = week; // this prototype has been written above
var fromISODate = getDateFromISOWeek(week, year);
var fromISODay = ("0" + fromISODate.getDate()).slice(-2);
var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);
var fromISOYear = date.getFullYear();
// Use long to return month like "December" or short for "Dec"
//var monthComplete = fullDate.toLocaleString(locale, { month: "long" });
var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;
var element = document.getElementById("fullDate");
element.value = formattedDate;
}
printDate();
document.getElementById("convertToDate").addEventListener("click", printDate);
*{
font-family: consolas
}
<label for="date">Date</label>
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />
<br /><br />
<label for="year">Year</label>
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />
-
<label for="week">Week</label>
<input type="text" id="week" style="width:25px;text-align:center" value="" />
<br /><br />
<label for="fullDate">Full Date</label>
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />
<br /><br />
<button id="convertToDate">
Convert Date
</button>
It's pure JS.
There are a bunch of date functions inside that allow you to convert date into week number and viceversa :)
Luxon is an other alternative. Luxon date objects have a weekNumber property:
let week = luxon.DateTime.fromString("2022-04-01", "yyyy-MM-dd").weekNumber;
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>
I've tried using code from all of the answers above, and all return week #52 for the first of January. So I decided to write my own, which calculates the week number correctly.
Week numeration starts from 0
Maybe it's a bad taste to use a loop, or the result can be cached somewhere to prevent repeating the same calculations if the function is called often enough. Well, I have made this for myself, and it does what I need it to do.
Date.prototype.getWeek = function() {
// debugger
let msWeek = 604800000; // Week in milliseconds
let msDay = 86400000; // Day in milliseconds
let year = this.getFullYear(); // Get the year
//let month = this.getMonth(); // Month
let oneDate = new Date(year, 0, 1); // Create a new date based on THIS year
let temp = oneDate.getDay(); // Ordinal of the first day
let getFirstDay = (temp === 0) ? 6 : temp - 1; // Ordinal of the first day of the current month (0-MO, 6-SU)
let countWeek = 0;
// Test to confirm week
oneDate = new Date(oneDate.getTime() + msDay*(7 - getFirstDay));
if(oneDate.getTime() > this.getTime()){
return countWeek;
}
// Increment loop
while(true){
oneDate = new Date(oneDate.getTime() + msWeek); // Add a week and check
if(oneDate.getTime() > this.getTime()) break;
countWeek++;
}
return countWeek + 1;
}
let s1 = new Date('2022-01-01'); console.log(s1.getWeek());
let s2 = new Date('2023-01-01'); console.log(s2.getWeek());
let s22 = new Date('2023-01-02'); console.log(s22.getWeek());
let s3 = new Date('2024-01-01'); console.log(s3.getWeek());
let s4 = new Date('2025-01-01'); console.log(s4.getWeek());
let s5 = new Date('2022-02-28'); console.log(s5.getWeek());
let s6 = new Date('2022-12-31'); console.log(s6.getWeek());
let s7 = new Date('2024-12-31'); console.log(s7.getWeek());
Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.
Here is a revised and working version:
Date.prototype.getWeek = function() {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
return 1 + Math.ceil(dayDiff / 7);
}
else { // jan 4th is on the next week (so next week is week 1)
return Math.ceil(dayDiff / 7);
}
};
Martin Schillinger's version seems to be the strictly correct one.
Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:
ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );
It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.

JavaScript - get the first day of the week from current date

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?
Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
You can then subtract that number of days plus one, for example:
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
getMonday(new Date()); // Mon Nov 08 2010
Not sure how it compares for performance, but this works.
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
Or as a function:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that add/subtract hours/minutes/seconds/milliseconds are wrong because not all days have 24 hours.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
First / Last Day of The Week
To get the upcoming first day of the week, you can use something like so:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - currentDay + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
Or to get the latest first day:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - (currentDay || 7));
return new Date(newDate);
}
console.log(getLastSunday());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* You can also format it using toISOString method like so: getLastSunday().toISOString()
Check out Date.js
Date.today().previous().monday()
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
I'm using this
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
Returns Monday 00am to Monday 00am.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
a more generalized version of this... this will give you any day in the current week based on what day you specify.
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
Simple solution for getting the first day of the week.
With this solution, it is possible to set an arbitrary start of week (e.g. Sunday = 0, Monday = 1, Tuesday = 2, etc.).
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
The solution correctly wraps on months (due to Date.setDate() being used)
For startOfWeek, the same constant numbers as in Date.getDay() can be used
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
An example of the mathematically only calculation, without any Date functions.
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
It is important to discern between local time and UTC. I wanted to find the start of the week in UTC, so I used the following function.
function start_of_week_utc(date, start_day = 1) {
// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.
date = new Date(date);
const day_of_month = date.getUTCDate();
const day_of_week = date.getUTCDay();
const difference_in_days = (
day_of_week >= start_day
? day_of_week - start_day
: day_of_week - start_day + 7
);
date.setUTCDate(day_of_month - difference_in_days);
date.setUTCHours(0);
date.setUTCMinutes(0);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
return date;
}
To find the start of the week in a given timezone, first add the timezone offset to the input date and then subtract it from the output date.
const local_start_of_week = new Date(
start_of_week_utc(
date.getTime() + timezone_offset_ms
).getTime() - timezone_offset_ms
);
I use this:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
It works fine.
Accepted answer won't work for anyone who runs the code in UTC-XX:XX timezone.
Here is code which will work regardless of timezone for date only. This won't work if you provide time too. Only provide date or parse date and provide it as input. I have mentioned different test cases at start of the code.
function getDateForTheMonday(dateString) {
var orignalDate = new Date(dateString)
var modifiedDate = new Date(dateString)
var day = modifiedDate.getDay()
diff = modifiedDate.getDate() - day + (day == 0 ? -6:1);// adjust when day is sunday
modifiedDate.setDate(diff)
var diffInDate = orignalDate.getDate() - modifiedDate.getDate()
if(diffInDate == 6) {
diff = diff + 7
modifiedDate.setDate(diff)
}
console.log("Given Date : " + orignalDate.toUTCString())
console.log("Modified date for Monday : " + modifiedDate)
}
getDateForTheMonday("2022-08-01") // Jul month with 31 Days
getDateForTheMonday("2022-07-01") // June month with 30 days
getDateForTheMonday("2022-03-01") // Non leap year February
getDateForTheMonday("2020-03-01") // Leap year February
getDateForTheMonday("2022-01-01") // First day of the year
getDateForTheMonday("2021-12-31") // Last day of the year
Extending answer from #Christian C. Salvadó and information from #Ayyash (object is mutable) and #Awi and #Louis Ameline (set hours to 00:00:00)
The function can be like this
function getMonday(d) {
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
d.setDate(diff);
d.setHours(0,0,0,0); // set hours to 00:00:00
return d; // object is mutable no need to recreate object
}
getMonday(new Date())
Check out: moment.js
Example:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Bonus: works with node.js too

Detect last week of each month with javascript

what would be a way in javascript to detect the last week of each (current) month. Or last monday of the month?
I would suggest to get the number of days in the month and then loop from the last day until getDay() gives back a Monday (1) or Sunday(0) .. based on when does your week start. Once you get your start date ... end date would be startDate + 7 so something along these lines
I found this helpful :
//Create a function that determines how many days in a month
//NOTE: iMonth is zero-based .. Jan is 0, Feb is 2 and so on ...
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
Then the loop:
//May - should return 31
var days_in_month = daysInMonth(4, 2010);
var weekStartDate = null;
var weekEndDate = null;
for(var i=days_in_month; i>0; i--)
{
var tmpDate = new Date(2010, 4, i);
//week starting on sunday
if(tmpDate.getDay() == 0)
{
weekStartDate = new Date(tmpDate);
weekEndDate = new Date(tmpDate.setDate(tmpDate.getDate() + 6));
//break out of the loop
break;
}
}
Playing with the date object and its methods you can do the following..
update
the complete calculations to get to last monday of the month could be compacted to
var d = new Date();
d.setMonth( d.getMonth() + 1 );
d.setDate(0);
lastmonday = d.getDate() - (d.getDay() - 1);
alert(lastmonday);
verbose example..
var now = new Date(); // get the current date
// calculate the last day of the month
if (now.getMonth() == 11 ) // if month is dec then go to next year and first month
{
nextmonth = 0;
nextyear = now.getFullYear() + 1;
}
else // otherwise go to next month of current year
{
nextmonth = now.getMonth() + 1;
nextyear = now.getFullYear();
}
var d = new Date( nextyear , nextmonth , 0); // setting day to 0 goes to last date of previous month
alert( d.getDay() ); // will alert the day of the week 0 being sunday .. you can calculate from there to get the first day of that week ..
Use getDay() to get the day of week of the last day in month and work from that (substracting the value from the number of days of the month should probably do the trick. +/- 1).
To determine whether it is a Monday, use .getDay() == 1. To determine if it is the last of the month, add seven days and compare months: nextMonday.setDate(monday.getDate()+7);
nextMonday.getMonth() == monday.getMonth();
The Javascript "Date" object is your friend.
function lastOfThisMonth(whichDay) {
var d= new Date(), month = d.getMonth();
d.setDate(1);
while (d.getDay() !== whichDay) d.setDate(d.getDate() + 1);
for (var n = 1; true; n++) {
var nd = new Date(d.getFullYear(), month, d.getDate() + n * 7);
if (nd.getMonth() !== month)
return new Date(d.getFullYear(), month, d.getDate() + (n - 1) * 7).getDate();
}
}
That'll give you the date (in the month, like 30) of the last day of the month that's the chosen day of the week (0 through 7).
Finding the last week of the month will depend on what you mean by that. If you mean the last complete week, then (if you mean Sunday - Saturday) find the last Saturday, and subtract 6. If you mean the last week that starts in the month, find the last Sunday.
You may also like to find the third Monday or the first Tuesday before or after a given date,
or flag every Wednesday between two dates.
Date.prototype.lastweek= function(wd, n){
n= n || 1;
return this.nextweek(wd, -n);
}
Date.prototype.nextweek= function(wd, n){
if(n== undefined) n= 1;
var incr= (n<0)? 1: -1,
D= new Date(this),
dd= D.getDay();
if(wd=== undefined) wd= dd;
if(dd!= wd) while(D.getDay()!= wd) D.setDate(D.getDate()+incr);
D.setDate(D.getDate()+7*n);
D.setHours(0, 0, 0, 0);
return D;
}
function lastMondayinmonth(month, year){
var day= new Date();
if(!month) month= day.getMonth()+1;
if(!year) year= day.getFullYear();
day.setFullYear(year, month, 0);
return day.lastweek(1);
}
alert(lastMondayinmonth())
i found such example that detects last monday of each week but it wont detect last monday of the month. maybe it will help to find better solution, that code looks short.
var dif, d = new Date(); // Today's date
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction
alert(d); // Last monday.
OK, so far i came up with such solution making it a bit of my own way and getting a few things mentioned here. It works correct and always returns the last monday of current month.
//function that will help to check how many days in month
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
var dif = null;
d = new Date(); // Today's date
countDays = daysInMonth(d.getMonth(),d.getFullYear()); //Checking number of days in current month
d.setDate(countDays); //setting the date to last day of the month
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction
alert(d.getDate()); //finally you get the last monday of the current month
Get the last day of the month:
/**
* Accepts either zero, one, or two parameters.
* If zero parameters: defaults to today's date
* If one parameter: Date object
* If two parameters: year, (zero-based) month
*/
function getLastDay() {
var year, month;
var lastDay = new Date();
if (arguments.length == 1) {
lastDay = arguments[0];
} else if (arguments.length > 0) {
lastDay.setYear(arguments[0]);
lastDay.setMonth(arguments[1]);
}
lastDay.setMonth(lastDay.getMonth() + 1);
lastDay.setDate(0);
return lastDay;
}
Get the last Monday:
/**
* Accepts same parameters as getLastDay()
*/
function getLastMonday() {
var lastMonday = getLastDay.apply(this, arguments);
lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay() == 0 ? 6 : (lastMonday.getDay() - 1)));
return lastMonday;
}
Get week of the year for a given day:
/**
* Accepts one parameter: Date object.
* Assumes start of week is Sunday.
*/
function getWeek(d) {
var jan1 = new Date(d.getFullYear(), 0, 1);
return Math.ceil((((d - jan1) / (24 * 60 * 60 * 1000)) + jan1.getDay() + 1) / 7);
}
Putting them together (assuming you're using Firebug):
// Get the last day of August 2006:
var august2006 = new Date(2006, 7);
var lastDayAugust2006 = getLastDay(august2006);
console.log("lastDayAugust2006: %s", lastDayAugust2006);
// ***** Testing getWeek() *****
console.group("***** Testing getWeek() *****");
// Get week of January 1, 2010 (Should be 1):
var january12010Week = getWeek(new Date(2010, 0, 1));
console.log("january12010Week: %s", january12010Week);
// Get week of January 2, 2010 (Should still be 1):
var january22010Week = getWeek(new Date(2010, 0, 2));
console.log("january22010Week: %s", january22010Week);
// Get week of January 3, 2010 (Should be 2):
var january32010Week = getWeek(new Date(2010, 0, 3));
console.log("january32010Week: %s", january32010Week);
console.groupEnd();
// *****************************
// Get the last week of this month:
var lastWeekThisMonth = getWeek(getLastDay());
console.log("lastWeekThisMonth: %s", lastWeekThisMonth);
// Get the last week of January 2007:
var lastWeekJan2007 = getWeek(getLastDay(2007, 0));
console.log("lastWeekJan2007: %s", lastWeekJan2007);
// Get the last Monday of this month:
var lastMondayThisMonth = getLastMonday();
console.log("lastMondayThisMonth: %s", lastMondayThisMonth);
// Get the week of the last Monday of this month:
var lastMondayThisMonthsWeek = getWeek(lastMondayThisMonth);
console.log("lastMondayThisMonthsWeek: %s", lastMondayThisMonthsWeek);

Categories

Resources