Get weeks in year - javascript

Moment js has a function to get the number of days in a month : http://momentjs.com/docs/#/displaying/days-in-month/
However I could not find a function to find the number of iso weeks in a year (52 or 53).

Here's an answer that isn't dependent on a library. It uses a function to calculate the week in the year that 31 December falls in for the required year. If the week is 1 (i.e. 31 December is in the first week of the following year), it moves the day number lower until it gets a different value, which will be the last week of the required year.
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(+d);
d.setHours(0, 0, 0, 0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// Get first day of year
var yearStart = new Date(d.getFullYear(), 0, 1);
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
// Return array of year and week number
return [d.getFullYear(), weekNo];
}
function weeksInYear(year) {
var month = 11,
day = 31,
week;
// Find week that 31 Dec is in. If is first week, reduce date until
// get previous week.
do {
d = new Date(year, month, day--);
week = getWeekNumber(d)[1];
} while (week == 1);
return week;
}
[2015, 2016, 2029, new Date().getFullYear()].forEach(year =>
console.log(`${year} has ${weeksInYear(year)} weeks`)
);
The getWeekNumber code is from here: Get week of year in JavaScript like in PHP.
Edit
Alternatively, if 31 December is in week 1 of the following year, then the subject year has 52 weeks and otherwise has 53 weeks.
function getWeekNumber(d) {
d = new Date(+d);
d.setHours(0, 0, 0, 0);
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
var yearStart = new Date(d.getFullYear(), 0, 1);
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
return [d.getFullYear(), weekNo];
}
function weeksInYear(year) {
var d = new Date(year, 11, 31);
var week = getWeekNumber(d)[1];
return week == 1 ? 52 : week;
}
[2015, 2016, 2029, new Date().getFullYear()].forEach(year =>
console.log(`${year} has ${weeksInYear(year)} weeks`)
);

Use isoWeek on the last day of the year to get the number of weeks e.g. :
function weeksInYear(year) {
return Math.max(
moment(new Date(year, 11, 31)).isoWeek()
, moment(new Date(year, 11, 31-7)).isoWeek()
);
}

Feb. 4th 2014 the weeksInYear & isoWeeksInYear functions were added to moment.js
So today you can just use moment().isoWeeksInYear()or moment().weeksInYear()
For more into see the docs

Thought I would post a much simpler version that I derived from the wikipedia article.
https://en.wikipedia.org/wiki/ISO_week_date
The statement in the article is:
"The number of weeks in a given year is equal to the corresponding
week number of 28 December, because it is the only date that is always
in the last week of the year since it is a week before 4 January which
is always in the first week of the following year.
Using only the ordinal year number y, the number of weeks in that year
can be determined from a function, that
returns the day of the week of 31 December"
Therefore getWeekFor(new Date(2022, 11, 28) replacing the year with any year you want will always give you the number of weeks for that year.
// modified from https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php
const getWeekFor = (date) => {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
const dayNum = d.getUTCDay() || 7;
const utc = new Date(d.setUTCDate(d.getUTCDate() + 4 - dayNum));
const yearStart = new Date(Date.UTC(utc.getUTCFullYear(), 0, 1)).getTime();
return Math.ceil(((d.getTime() - yearStart) / 86400000 + 1) / 7);
};
const weeks = getWeekFor(new Date(2020, 11, 28)) // 53.
console.log(weeks);

Get all weeks and periods of that week for a year, for whom it may interest
function getWeekPeriodsInYear(year) {
weeks = [];
// Get the first and last day of the year
currentDay = moment([year, 1]).startOf('year');
dayOfWeek = moment(currentDay).day();
lastDay = moment([year, 1]).endOf('year');
weeksInYear = moment(`${year}-01-01`).isoWeeksInYear();
daysToAdd = 7 - dayOfWeek;
for (let weekNumber = 1; weekNumber < weeksInYear + 1; weekNumber++) {
let endOfWeek = moment(currentDay).add(daysToAdd, 'days');
if (moment(endOfWeek).year() !== year) {
endOfWeek = lastDay;
}
weeks.push({ weekNumber, start: currentDay.toDate(), end: endOfWeek.toDate() });
currentDay = endOfWeek.add(1, 'day');
daysToAdd = 6;
}
return weeks;
}
getWeekPeriodsInYear(new Date().getFullYear()).forEach(period =>
document.write(`Week ${period.weekNumber} from ${moment(period.start).format('DD-MM-YYYY')} up to and including ${moment(period.end).format('DD-MM-YYYY')}<br/>`)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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 to get current week number in javascript? [duplicate]

How do I get the current weeknumber of the year, like PHP's date('W')?
It should be the ISO-8601 week number of year, weeks starting on Monday.
You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.
A better link on the same site is: Working with weeks.
Edit
Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.
Edit 2017
There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.
/* For a given date, get the ISO week number
*
* Based on information at:
*
* THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}
var result = getWeekNumber(new Date());
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);
Hours are zeroed when creating the "UTC" date.
Minimized, prototype version (returns only week-number):
Date.prototype.getWeekNumber = function(){
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
};
document.write('The current ISO week number is ' + new Date().getWeekNumber());
Test section
In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050).
Date.prototype.getWeekNumber = function(){
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
};
function checkWeek() {
var s = document.getElementById('dString').value;
var m = moment(s, 'YYYY-MM-DD');
document.getElementById('momentWeek').value = m.format('W');
document.getElementById('answerWeek').value = m.toDate().getWeekNumber();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Enter date YYYY-MM-DD: <input id="dString" value="2021-02-22">
<button onclick="checkWeek(this)">Check week number</button><br>
Moment: <input id="momentWeek" readonly><br>
Answer: <input id="answerWeek" readonly>
You can use momentjs library also:
moment().format('W')
Not ISO-8601 week number but if the search engine pointed you here anyway.
As said above but without a class:
let now = new Date();
let onejan = new Date(now.getFullYear(), 0, 1);
let week = Math.ceil((((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);
console.log(week);
Accordily http://javascript.about.com/library/blweekyear.htm
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
var millisecsInDay = 86400000;
return Math.ceil((((this - onejan) / millisecsInDay) + onejan.getDay() + 1) / 7);
};
let d = new Date(2020,11,30);
for (let i=0; i<14; i++) {
console.log(`${d.toDateString()} is week ${d.getWeek()}`);
d.setDate(d.getDate() + 1);
}
Jacob Wright's Date.format() library implements date formatting in the style of PHP's date() function and supports the ISO-8601 week number:
new Date().format('W');
It may be a bit overkill for just a week number, but it does support PHP style formatting and is quite handy if you'll be doing a lot of this.
The code below calculates the correct ISO 8601 week number. It matches PHP's date("W") for every week between 1/1/1970 and 1/1/2100.
/**
* 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 1st
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 week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((firstThursday - target) / 604800000);
}
Source: Taco van den Broek
If you're not into extending prototypes, then here's a function:
function getWeek(date) {
if (!(date instanceof Date)) date = new Date();
// ISO week date weeks start on Monday, so correct the day number
var nDay = (date.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
date.setDate(date.getDate() - nDay + 3);
// Store the millisecond value of the target date
var n1stThursday = date.valueOf();
// Set the target to the first Thursday of the year
// First, set the target to January 1st
date.setMonth(0, 1);
// Not a Thursday? Correct the date to the next Thursday
if (date.getDay() !== 4) {
date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
}
// The week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((n1stThursday - date) / 604800000);
}
Sample usage:
getWeek(); // Returns 37 (or whatever the current week is)
getWeek(new Date('Jan 2, 2011')); // Returns 52
getWeek(new Date('Jan 1, 2016')); // Returns 53
getWeek(new Date('Jan 4, 2016')); // Returns 1
getWeekOfYear: function(date) {
var target = new Date(date.valueOf()),
dayNumber = (date.getUTCDay() + 6) % 7,
firstThursday;
target.setUTCDate(target.getUTCDate() - dayNumber + 3);
firstThursday = target.valueOf();
target.setUTCMonth(0, 1);
if (target.getUTCDay() !== 4) {
target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
}
return Math.ceil((firstThursday - target) / (7 * 24 * 3600 * 1000)) + 1;
}
Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601
Get the weeknumber of any given Date
function week(year,month,day) {
function serial(days) { return 86400000*days; }
function dateserial(year,month,day) { return (new Date(year,month-1,day).valueOf()); }
function weekday(date) { return (new Date(date)).getDay()+1; }
function yearserial(date) { return (new Date(date)).getFullYear(); }
var date = year instanceof Date ? year.valueOf() : typeof year === "string" ? new Date(year).valueOf() : dateserial(year,month,day),
date2 = dateserial(yearserial(date - serial(weekday(date-serial(1))) + serial(4)),1,3);
return ~~((date - date2 + serial(weekday(date2) + 5))/ serial(7));
}
Example
console.log(
week(2016, 06, 11),//23
week(2015, 9, 26),//39
week(2016, 1, 1),//53
week(2016, 1, 4),//1
week(new Date(2016, 0, 4)),//1
week("11 january 2016")//2
);
I found useful the Java SE's SimpleDateFormat class described on Oracle's specification:
http://goo.gl/7MbCh5. In my case in Google Apps Script it worked like this:
function getWeekNumber() {
var weekNum = parseInt(Utilities.formatDate(new Date(), "GMT", "w"));
Logger.log(weekNum);
}
For example in a spreadsheet macro you can retrieve the actual timezone of the file:
function getWeekNumber() {
var weekNum = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "w"));
Logger.log(weekNum);
}
This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.
/**
* Get week number in the year.
* #param {Integer} [weekStart=0] First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
* #return {Integer} 0-based number of week.
*/
Date.prototype.getWeek = function(weekStart) {
var januaryFirst = new Date(this.getFullYear(), 0, 1);
if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
throw new Error('Wrong argument. Must be an integer between 0 and 6.');
}
weekStart = weekStart || 0;
return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};
If you are already in an Angular project you could use $filter('date').
For example:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
The code snippet which works pretty well for me is this one:
var yearStart = +new Date(d.getFullYear(), 0, 1);
var today = +new Date(d.getFullYear(),d.getMonth(),d.getDate());
var dayOfYear = ((today - yearStart + 1) / 86400000);
return Math.ceil(dayOfYear / 7).toString();
Note:
d is my Date for which I want the current week number.
The + converts the Dates into numbers (working with TypeScript).
With Luxon (https://github.com/moment/luxon) :
import { DateTime } from 'luxon';
const week: number = DateTime.fromJSDate(new Date()).weekNumber;
This week number thing has been a real pain in the a**. Most trivial solutions around the web didn't really work for me as they worked most of the time but all of them broke at some point, especially when year changed and last week of the year was suddenly next year's first week etc. Even Angular's date filter showed incorrect data (it was the 1st week of next year, Angular gave week 53).
Note: The examples are designed to work with European weeks (Mon first)!
getWeek()
Date.prototype.getWeek = function(){
// current week's Thursday
var curWeek = new Date(this.getTime());
curWeek.setDay(4);
// current year's first week's Thursday
var firstWeek = new Date(curWeek.getFullYear(), 0, 4);
firstWeek.setDay(4);
return (curWeek.getDayIndex() - firstWeek.getDayIndex()) / 7 + 1;
};
setDay()
/**
* Make a setDay() prototype for Date
* Sets week day for the date
*/
Date.prototype.setDay = function(day){
// Get day and make Sunday to 7
var weekDay = this.getDay() || 7;
var distance = day - weekDay;
this.setDate(this.getDate() + distance);
return this;
}
getDayIndex()
/*
* Returns index of given date (from Jan 1st)
*/
Date.prototype.getDayIndex = function(){
var start = new Date(this.getFullYear(), 0, 0);
var diff = this - start;
var oneDay = 86400000;
return Math.floor(diff / oneDay);
};
I have tested this and it seems to be working very well but if you notice a flaw in it, please let me know.
Here is my implementation for calculating the week number in JavaScript. corrected for summer and winter time offsets as well.
I used the definition of the week from this article: ISO 8601
Weeks are from mondays to sunday, and january 4th is always in the first week of the year.
// add get week prototype functions
// weeks always start from monday to sunday
// january 4th is always in the first week of the year
Date.prototype.getWeek = function () {
year = this.getFullYear();
var currentDotw = this.getWeekDay();
if (this.getMonth() == 11 && this.getDate() - currentDotw > 28) {
// if true, the week is part of next year
return this.getWeekForYear(year + 1);
}
if (this.getMonth() == 0 && this.getDate() + 6 - currentDotw < 4) {
// if true, the week is part of previous year
return this.getWeekForYear(year - 1);
}
return this.getWeekForYear(year);
}
// returns a zero based day, where monday = 0
// all weeks start with monday
Date.prototype.getWeekDay = function () {
return (this.getDay() + 6) % 7;
}
// corrected for summer/winter time
Date.prototype.getWeekForYear = function (year) {
var currentDotw = this.getWeekDay();
var fourjan = new Date(year, 0, 4);
var firstDotw = fourjan.getWeekDay();
var dayTotal = this.getDaysDifferenceCorrected(fourjan) // the difference in days between the two dates.
// correct for the days of the week
dayTotal += firstDotw; // the difference between the current date and the first monday of the first week,
dayTotal -= currentDotw; // the difference between the first monday and the current week's monday
// day total should be a multiple of 7 now
var weeknumber = dayTotal / 7 + 1; // add one since it gives a zero based week number.
return weeknumber;
}
// corrected for timezones and offset
Date.prototype.getDaysDifferenceCorrected = function (other) {
var millisecondsDifference = (this - other);
// correct for offset difference. offsets are in minutes, the difference is in milliseconds
millisecondsDifference += (other.getTimezoneOffset()- this.getTimezoneOffset()) * 60000;
// return day total. 1 day is 86400000 milliseconds, floor the value to return only full days
return Math.floor(millisecondsDifference / 86400000);
}
for testing i used the following JavaScript tests in Qunit
var runweekcompare = function(result, expected) {
equal(result, expected,'Week nr expected value: ' + expected + ' Actual value: ' + result);
}
test('first week number test', function () {
expect(5);
var temp = new Date(2016, 0, 4); // is the monday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 4, 23, 50); // is the monday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 10, 23, 50); // is the sunday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 11, 23, 50); // is the second week of the year
runweekcompare(temp.getWeek(), 2);
var temp = new Date(2016, 1, 29, 23, 50); // is the 9th week of the year
runweekcompare(temp.getWeek(), 9);
});
test('first day is part of last years last week', function () {
expect(2);
var temp = new Date(2016, 0, 1, 23, 50); // is the first last week of the previous year
runweekcompare(temp.getWeek(), 53);
var temp = new Date(2011, 0, 2, 23, 50); // is the first last week of the previous year
runweekcompare(temp.getWeek(), 52);
});
test('last day is part of next years first week', function () {
var temp = new Date(2013, 11, 30); // is part of the first week of 2014
runweekcompare(temp.getWeek(), 1);
});
test('summer winter time change', function () {
expect(2);
var temp = new Date(2000, 2, 26);
runweekcompare(temp.getWeek(), 12);
var temp = new Date(2000, 2, 27);
runweekcompare(temp.getWeek(), 13);
});
test('full 20 year test', function () {
//expect(20 * 12 * 28 * 2);
for (i = 2000; i < 2020; i++) {
for (month = 0; month < 12; month++) {
for (day = 1; day < 29 ; day++) {
var temp = new Date(i, month, day);
var expectedweek = temp.getWeek();
var temp2 = new Date(i, month, day, 23, 50);
var resultweek = temp.getWeek();
equal(expectedweek, Math.round(expectedweek), 'week number whole number expected ' + Math.round(expectedweek) + ' resulted week nr ' + expectedweek);
equal(resultweek, expectedweek, 'Week nr expected value: ' + expectedweek + ' Actual value: ' + resultweek + ' for year ' + i + ' month ' + month + ' day ' + day);
}
}
}
});
Here is a slight adaptation for Typescript that will also return the dates for the week start and week end. I think it's common to have to display those in a user interface, since people don't usually remember week numbers.
function getWeekNumber(d: Date) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number Make
// Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
// Get first day of year
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
// Calculate full weeks to nearest Thursday
const weekNo = Math.ceil(
((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7
);
const weekStartDate = new Date(d.getTime());
weekStartDate.setUTCDate(weekStartDate.getUTCDate() - 3);
const weekEndDate = new Date(d.getTime());
weekEndDate.setUTCDate(weekEndDate.getUTCDate() + 3);
return [d.getUTCFullYear(), weekNo, weekStartDate, weekEndDate] as const;
}
This is my typescript implementation which I tested against some dates. This implementation allows you to set the first day of the week to any day.
//sunday = 0, monday = 1, ...
static getWeekNumber(date: Date, firstDay = 1): number {
const d = new Date(date.getTime());
d.setHours(0, 0, 0, 0);
//Set to first day of the week since it is the same weeknumber
while(d.getDay() != firstDay){
d.setDate(d.getDate() - 1);
}
const dayOfYear = this.getDayOfYear(d);
let weken = Math.floor(dayOfYear/7);
// add an extra week if 4 or more days are in this year.
const daysBefore = ((dayOfYear % 7) - 1);
if(daysBefore >= 4){
weken += 1;
}
//if the last 3 days onf the year,it is the first week
const t = new Date(d.getTime());
t.setDate(t.getDate() + 3);
if(t.getFullYear() > d.getFullYear()){
return 1;
}
weken += 1;
return weken;
}
private static getDayOfYear(date: Date){
const start = new Date(date.getFullYear(), 0, 0);
const diff = (date.getTime() - start.getTime()) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
return day;
}
Tests:
describe('getWeeknumber', () => {
it('should be ok for 0 sunday', () => {
expect(DateUtils.getWeekNumber(new Date(2015, 0, 4), 0)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 1), 0)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 2), 0)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 8), 0)).toBe(2);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 9), 0)).toBe(2);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 28), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 29), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 30), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 31), 0)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2022, 0, 3), 0)).toBe(1);
});
it('should be ok for monday 1 default', () => {
expect(DateUtils.getWeekNumber(new Date(2015, 0, 4), 1)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 1), 1)).toBe(52);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 2), 1)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 8), 1)).toBe(1);
expect(DateUtils.getWeekNumber(new Date(2017, 0, 9), 1)).toBe(2);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 28), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 29), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 30), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2020, 11, 31), 1)).toBe(53);
expect(DateUtils.getWeekNumber(new Date(2022, 0, 3), 1)).toBe(1);
});
});
I tried a lot to get the shortest code to get the weeknumber ISO-conform.
Date.prototype.getWeek=function(){
var date=new Date(this);
date.setHours(0,0,0,0);
return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
The variable date is necessary to avoid to alter the original this. I used the return values of setDate() and setMonth() to dispense with getTime() to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this is Date or Number of milliseconds, return value is String e.g. "49/2017".
Another library-based option: use d3-time-format:
const formatter = d3.timeFormat('%U');
const weekNum = formatter(new Date());
Shortest workaround for Angular2+ DatePipe, adjusted for ISO-8601:
import {DatePipe} from "#angular/common";
public rightWeekNum: number = 0;
constructor(private datePipe: DatePipe) { }
calcWeekOfTheYear(dateInput: Date) {
let falseWeekNum = parseInt(this.datePipe.transform(dateInput, 'ww'));
this.rightWeekNum = (dateInput.getDay() == 0) ? falseWeekNumber-1 : falseWeekNumber;
}
Inspired from RobG's answer.
What I wanted is the day of the week of a given date. So my answer is simply based on the day of the week Sunday. But you can choose the other day (i.e. Monday, Tuesday...);
First I find the Sunday in a given date and then calculate the week.
function getStartWeekDate(d = null) {
const now = d || new Date();
now.setHours(0, 0, 0, 0);
const sunday = new Date(now);
sunday.setDate(sunday.getDate() - sunday.getDay());
return sunday;
}
function getWeek(date) {
const sunday = getStartWeekDate(date);
const yearStart = new Date(Date.UTC(2021, 0, 1));
const weekNo = Math.ceil((((sunday - yearStart) / 86400000) + 1) / 7);
return weekNo;
}
// tests
for (let i = 0; i < 7; i++) {
let m = 14 + i;
let x = getWeek(new Date(2021, 2, m));
console.log('week num: ' + x, x + ' == ' + 11, x == 11, m);
}
for (let i = 0; i < 7; i++) {
let m = 21 + i;
let x = getWeek(new Date(2021, 2, m));
console.log('week num: ' + x, x + ' == ' + 12, x == 12, 'date day: ' + m);
}
for (let i = 0; i < 4; i++) {
let m = 28 + i;
let x = getWeek(new Date(2021, 2, m));
console.log('week num: ' + x, x + ' == ' + 13, x == 13, 'date day: ' + m);
}
for (let i = 0; i < 3; i++) {
let m = 1 + i;
let x = getWeek(new Date(2021, 3, m));
console.log('week num: ' + x, x + ' == ' + 13, x == 13, 'date day: ' + m);
}
for (let i = 0; i < 7; i++) {
let m = 4 + i;
let x = getWeek(new Date(2021, 3, m));
console.log('week num: ' + x, x + ' == ' + 14, x == 14, 'date day: ' + m);
}
now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);
function getWeek(param) {
let onejan = new Date(param.getFullYear(), 0, 1);
return Math.ceil((((param.getTime() - onejan.getTime()) / 86400000) + onejan.getDay()) / 7);
}

jquery/javascript- calculate days on this week given week number and year number

i'm looking for a simple way to calculate the calendar days when given a week and year number using jquery/javascript.
Example: Week 18, Year 2012 would result in a list of starting with sunday
2012-04-29
2012-04-30
2012-05-01
2012-05-02
2012-05-03
2012-05-04
2012-05-05
thanks
If you remake the code from this question you will get something like this:
function getDays(year, week) {
var j10 = new Date(year, 0, 10, 12, 0, 0),
j4 = new Date(year, 0, 4, 12, 0, 0),
mon = j4.getTime() - j10.getDay() * 86400000,
result = [];
for (var i = -1; i < 6; i++) {
result.push(new Date(mon + ((week - 1) * 7 + i) * 86400000));
}
return result;
}
DEMO: http://jsfiddle.net/TtmPt/
You need to decide what day begins a week - you specified Sunday. (ISO weeks start on Monday).
Get the day of the week of Jan 1.
Get the date of the closest Sunday.
If Jan 1 is on a Thursday, Friday, Saturday or Sunday, the first week of the year begins a week from the last Sunday in December. Otherwise, the first week of the year begins on the last Sunday of December.
Find the first day of any week of the year by setting the date to the first day + (weeks * 7) - 7.
var year= new Date().getFullYear(),
firstDay= new Date(year, 0, 1),
wd= firstDay.getDay();
firstDay.setDate(1 +(-1*(wd%7)));
if(wd>3){
firstDay.setDate(firstDay.getDate()+ 7);
}
var week4= new Date(firstDay);
week4.setDate(week4.getDate()+(4*7)- 7);
alert(week4);
returned value:(Date)
Sun Jan 20 2013 00: 00: 00 GMT-0500(Eastern Standard Time)
jquery/javascript- calculate days on this week given week number and year number
var years = $('#yr').val();
var weeks = $('#weekNo').val();
var d = new Date(years, 0, 1);
var dayNum = d.getDay();
var diff = --weeks * 7;
if (!dayNum || dayNum > 4) {
diff += 7;
}
d.setDate(d.getDate() - d.getDay() + ++diff);
$('#result').val(d);
[Demo] [1]: https://jsfiddle.net/2bhLw084/

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

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