Get week of year in JavaScript like in PHP - javascript

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

Related

Get next day, skip weekends

I want to generate next working day using JavaScript.
This is my code as of now
var today = new Date();
today.setDate(today.getDate());
var tdd = today.getDate();
var tmm = today.getMonth()+1;
var tyyyy = today.getYear();
var date = new Date();
date.setDate(date.getDate()+3);
Problem is, on Fridays it returns Saturday's date whereas I want it to be Monday
This will choose the next working day when a date is passed to it.
I suggest you normalise the date you pass, so you will not be surprised around summertime/wintertime change
Updated in 2023
const getNextWork = date => {
let day = date.getDay(), add = 1;
if (day === 6) add = 2; else
if (day === 5) add = 3;
date.setDate(date.getDate() + add); // will correctly handle 31+1 > 32 > 1st next month
return date;
};
// tests:
const dt = new Intl.DateTimeFormat("en-US", {
weekday: "short",
year: "numeric",
month: "long",
day: "numeric",
timeZone: "UTC",
timeZoneName: "short",
hour: "numeric",
minute: "numeric",
});
const aDay = 24 * 60 * 60 * 1000;
// 26th of March 2023 is daylight savings date in my country
let date = new Date(2023, 2, 24, 15, 0, 0, 0).getTime();
for (let i = 0; i < 7; i++) {
const d = new Date(date + i * aDay);
console.log(dt.format(d), "-->", dt.format(getNextWork(d)));
}
Older code:
var today = new Date(2016, 7, 26,12,0,0,0,0); // Friday at noon
console.log("today, Monday",today,"day #"+today.getDay());
var next = new Date(today.getTime());
next.setDate(next.getDate()+1); // tomorrow
while (next.getDay() == 6 || next.getDay() == 0) next.setDate(next.getDate() + 1);
console.log("no change ",next,"day #"+next.getDay());
console.log("-------");
// or without a loop:
function getNextWork(d) {
d.setDate(d.getDate()+1); // tomorrow
if (d.getDay()==0) d.setDate(d.getDate()+1);
else if (d.getDay()==6) d.setDate(d.getDate()+2);
return d;
}
next = getNextWork(today); // Friday
console.log("today, Friday",today);
console.log("next, Monday ",next);
console.log("-------");
today = new Date(2016, 7, 29,12,0,0,0); // Monday at noon
next = getNextWork(today); // Still Monday at noon
console.log("today, Monday",today);
console.log("no change ",next);
console.log("-------");
// Implementing Rob's comment
function getNextWork1(d) {
var day = d.getDay(),add=1;
if (day===5) add=3;
else if (day===6) add=2;
d.setDate(d.getDate()+add);
return d;
}
today = new Date(2016, 7, 26,12,0,0,0,0); // Friday at noon
next = getNextWork1(today); // Friday
console.log("today, Friday",today);
console.log("next, Monday ",next);
console.log("-------");
today = new Date(2016, 7, 26,12,0,0,0,0); // Monday at noon
next = getNextWork1(today); // Monday
console.log("today, Monday",today);
console.log("no change ",next);
You can add 1 day at at time until you get to a day that isn't Saturday or Sunday:
function getNextBusinessDay(date) {
// Copy date so don't affect original
date = new Date(+date);
// Add days until get not Sat or Sun
do {
date.setDate(date.getDate() + 1);
} while (!(date.getDay() % 6))
return date;
}
// today, Friday 26 Aug 2016
[new Date(), new Date(2016,7,26)].forEach(function(d) {
console.log(d.toLocaleString() + ' : ' + getNextBusinessDay(d).toLocaleString());
});
You can also test the day and add extra to get over the weekend:
// Classic Mon to Fri
function getNextWorkDay(date) {
let d = new Date(+date);
let day = d.getDay() || 7;
d.setDate(d.getDate() + (day > 4? 8 - day : 1));
return d;
}
for (let i=0, d=new Date(); i<7; i++) {
console.log(`${d.toDateString()} -> ${getNextWorkDay(d).toDateString()}`);
d.setDate(d.getDate() + 1);
}
Here is another approach where the work week can be specified using ECMAScript weekday numbers (Sun = 0, Mon = 1, etc.). Dates outside the range are shifted to the start of the next work week.
This is useful where the week is not the classic Mon to Fri, such as the Middle East where Sat to Wed is common or for some who might work Fri to Mon (or whatever).
function getNext(start, end, date) {
let d = new Date(+date);
d.setDate(d.getDate() + 1);
let day = d.getDay();
// Adjust end and day if necessary
// The order of tests and adjustment is important
if (end < start) {
if (day <= end) {
day += 7;
}
end += 7;
}
// If day is before start, shift to start
if (day < start) {
d.setDate(d.getDate() + start - day);
// If day is after end, shift to next start (treat Sunday as 7)
} else if (day > end) {
d.setDate(d.getDate() + 8 - (day || 7));
}
return d;
}
// Examples
let f = new Intl.DateTimeFormat('en-GB', {
weekday:'short',day:'2-digit', month:'short'});
let d = new Date();
[{c:'Work days Mon to Fri',s:1,e:5},
{c:'Work days Sat to Wed',s:6,e:3},
{c:'Work days Fri to Mon',s:5,e:1}
].forEach(({c,s,e}) => {
for (let i = 0; i < 7; i++) {
!i? console.log(`\n${c}`) : null;
console.log(`${f.format(d)} => ${f.format(getNext(s, e, d))}`);
d.setDate(d.getDate() + 1);
}
});
Check this out: https://jsfiddle.net/e9a4066r/
function get_next_weekday (date) {
var tomorrow = new Date(date.setDate(date.getDate() + 1))
return tomorrow.getDay() % 6
? tomorrow
: get_next_weekday(tomorrow)
}
The accepted answer will skip one day at a time, which answers the OPs question, but for anyone looking to add a variable number of days while still skipping weekends the function below may be helpful:
function addWorkDays(date, days) {
while (days > 0) {
date.setDate(date.getDate() + 1);
if (date.getDay() != 0 && date.getDay() != 6) {
days -= 1;
}
}
return date;
}
Thought I'd throw my hat in the ring here with:
function getNextBusinessDate(date) {
// Create date array [S, M, T, W, T, F, S]
const days = new Array(7);
let nextDate = date;
for(let i = 0; i < 7; i++) {
days[nextDate.getDay()] = new Date(nextDate);
nextDate.setDate(nextDate.getDate() + 1);
}
// Shift indices to index as though array was [M, T, W, T, F, S, S]
// Then truncate with min to make F, S, S all yield M for next date
return days[Math.min((date.getDay() + 6) % 7 + 1, 5) % 5 + 1];
}

Get a given weekday in a given month with JavaScript

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

JavaScript Date.getWeek()? [duplicate]

This question already has answers here:
Get week of year in JavaScript like in PHP
(23 answers)
Closed 5 years ago.
I'm looking for a tested solid solution for getting current week of the year for specified date. All I can find are the ones that doesn't take in account leap years or just plain wrong. Does anyone have this type of stuff?
Or even better a function that says how many weeks does month occupy. It is usually 5, but can be 4 (feb) or 6 (1st is sunday and month has 30-31 days in it)
=================
UPDATE:
Still not sure about getting week #, but since I figured out it won't solve my problem with calculating how many weeks month occupy, I abandoned it.
Here's a function to find out how many weeks exactly month occupy on the calendar:
getWeeksNum: function(year, month) {
var daysNum = 32 - new Date(year, month, 32).getDate(),
fDayO = new Date(year, month, 1).getDay(),
fDay = fDayO ? (fDayO - 1) : 6,
weeksNum = Math.ceil((daysNum + fDay) / 7);
return weeksNum;
}
/**
* Returns the week number for this date. dowOffset is the day of week the week
* "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
* the week returned is the ISO 8601 week number.
* #param int dowOffset
* #return int
*/
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
dowOffset = typeof(dowOffset) == 'number' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};
Usage:
var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());
Source
For those looking for a more simple approach;
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan + 86400000)/86400000);
return Math.ceil(dayOfYear/7)
};
Use with:
var today = new Date();
var currentWeekNumber = today.getWeek();
console.log(currentWeekNumber);
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)
Get week number
Date.prototype.getWeek = function() {
var dt = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - dt) / 86400000) + dt.getDay()+1)/7);
};
var myDate = new Date(2013, 3, 25); // 2013, 25 April
console.log(myDate.getWeek());
I know this is an old question, but maybe it helps:
http://weeknumber.net/how-to/javascript
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: https://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);
}
// Returns the four-digit year corresponding to the ISO week of the date.
Date.prototype.getWeekYear = function() {
var date = new Date(this.getTime());
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
return date.getFullYear();
}
/*get the week number by following the norms of ISO 8601*/
function getWeek(dt){
var calc=function(o){
if(o.dtmin.getDay()!=1){
if(o.dtmin.getDay()<=4 && o.dtmin.getDay()!=0)o.w+=1;
o.dtmin.setDate((o.dtmin.getDay()==0)? 2 : 1+(7-o.dtmin.getDay())+1);
}
o.w+=Math.ceil((((o.dtmax.getTime()-o.dtmin.getTime())/(24*60*60*1000))+1)/7);
},getNbDaysInAMonth=function(year,month){
var nbdays=31;
for(var i=0;i<=3;i++){
nbdays=nbdays-i;
if((dtInst=new Date(year,month-1,nbdays)) && dtInst.getDate()==nbdays && (dtInst.getMonth()+1)==month && dtInst.getFullYear()==year)
break;
}
return nbdays;
};
if(dt.getMonth()+1==1 && dt.getDate()>=1 && dt.getDate()<=3 && (dt.getDay()>=5 || dt.getDay()==0)){
var pyData={"dtmin":new Date(dt.getFullYear()-1,0,1,0,0,0,0),"dtmax":new Date(dt.getFullYear()-1,11,getNbDaysInAMonth(dt.getFullYear()-1,12),0,0,0,0),"w":0};
calc(pyData);
return pyData.w;
}else{
var ayData={"dtmin":new Date(dt.getFullYear(),0,1,0,0,0,0),"dtmax":new Date(dt.getFullYear(),dt.getMonth(),dt.getDate(),0,0,0,0),"w":0},
nd12m=getNbDaysInAMonth(dt.getFullYear(),12);
if(dt.getMonth()==12 && dt.getDay()!=0 && dt.getDay()<=3 && nd12m-dt.getDate()<=3-dt.getDay())ayData.w=1;else calc(ayData);
return ayData.w;
}
}
alert(getWeek(new Date(2017,01-1,01)));

How to convert a week number to a date in Javascript

I had tried to find some work done but I haven't had luck. Any ideas?
Examples:
Week, 1, 2001 => 2001-01-01
Week, 26, 2007 => 2007-06-01
As Kevin's code does not implement ISO 8601 properly (first day of the first week of year must be a Monday), I've corrected it and ended up with (also check it on jsfiddle):
function firstDayOfWeek(week, year) {
if (year==null) {
year = (new Date()).getFullYear();
}
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = date.getTime() + weekTime;
return date.setTime(targetTime);
}
function weeksToMilliseconds(weeks) {
return 1000 * 60 * 60 * 24 * 7 * (weeks - 1);
}
function firstWeekOfYear(year) {
var date = new Date();
date = firstDayOfYear(date,year);
date = firstWeekday(date);
return date;
}
function firstDayOfYear(date, year) {
date.setYear(year);
date.setDate(1);
date.setMonth(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
/**
* Sets the given date as the first day of week of the first week of year.
*/
function firstWeekday(firstOfJanuaryDate) {
// 0 correspond au dimanche et 6 correspond au samedi.
var FIRST_DAY_OF_WEEK = 1; // Monday, according to iso8601
var WEEK_LENGTH = 7; // 7 days per week
var day = firstOfJanuaryDate.getDay();
day = (day === 0) ? 7 : day; // make the days monday-sunday equals to 1-7 instead of 0-6
var dayOffset=-day+FIRST_DAY_OF_WEEK; // dayOffset will correct the date in order to get a Monday
if (WEEK_LENGTH-day+1<4) {
// the current week has not the minimum 4 days required by iso 8601 => add one week
dayOffset += WEEK_LENGTH;
}
return new Date(firstOfJanuaryDate.getTime()+dayOffset*24*60*60*1000);
}
function assertDateEquals(effectiveDate, expectedDate, description) {
if ((effectiveDate==null ^ expectedDate==null) || effectiveDate.getTime()!=expectedDate.getTime()) {
console.log("assert failed: "+description+"; effective="+effectiveDate+", expected="+expectedDate);
}
}
function assertEquals(effectiveValue, expectedValue, description) {
if (effectiveValue!=expectedValue) {
console.log("assert failed: "+description+"; effective="+effectiveValue+", expected="+expectedValue);
}
}
// expect the first day of year to be a monday
for (var i=1970; i<2050; i++) {
assertEquals(firstWeekOfYear(i).getDay(), 1, "first day of year "+i+" must be a monday"); // 1=Monday
}
// assert some future first day of first week of year; source: http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
assertDateEquals(firstWeekOfYear(2013), new Date(Date.parse("Dec 31, 2012")), "2013");
assertDateEquals(firstWeekOfYear(2014), new Date(Date.parse("Dec 30, 2013")), "2014");
assertDateEquals(firstWeekOfYear(2015), new Date(Date.parse("Dec 29, 2014")), "2015");
assertDateEquals(firstWeekOfYear(2016), new Date(Date.parse("Jan 4, 2016")), "2016");
assertDateEquals(firstWeekOfYear(2017), new Date(Date.parse("Jan 2, 2017")), "2017");
assertDateEquals(firstWeekOfYear(2018), new Date(Date.parse("Jan 1, 2018")), "2018");
assertDateEquals(firstWeekOfYear(2019), new Date(Date.parse("Dec 31, 2018")), "2019");
assertDateEquals(firstWeekOfYear(2020), new Date(Date.parse("Dec 30, 2019")), "2020");
assertDateEquals(firstWeekOfYear(2021), new Date(Date.parse("Jan 4, 2021")), "2021");
assertDateEquals(firstWeekOfYear(2022), new Date(Date.parse("Jan 3, 2022")), "2022");
assertDateEquals(firstWeekOfYear(2023), new Date(Date.parse("Jan 2, 2023")), "2023");
assertDateEquals(firstWeekOfYear(2024), new Date(Date.parse("Jan 1, 2024")), "2024");
assertDateEquals(firstWeekOfYear(2025), new Date(Date.parse("Dec 30, 2024")), "2025");
assertDateEquals(firstWeekOfYear(2026), new Date(Date.parse("Dec 29, 2025")), "2026");
console.log("All assertions done.");
I included test cases for some dates to check that the first day of the first week of year is a Monday and checked some dates based on http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
Someone might be still interested in a more contained version:
function firstDayOfWeek (year, week) {
// Jan 1 of 'year'
var d = new Date(year, 0, 1),
offset = d.getTimezoneOffset();
// ISO: week 1 is the one with the year's first Thursday
// so nearest Thursday: current date + 4 - current day number
// Sunday is converted from 0 to 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// 7 days * (week - overlapping first week)
d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000
* (week + (year == d.getFullYear() ? -1 : 0 )));
// daylight savings fix
d.setTime(d.getTime()
+ (d.getTimezoneOffset() - offset) * 60 * 1000);
// back to Monday (from Thursday)
d.setDate(d.getDate() - 3);
return d;
}
I took the original idea from Kevin, with some tweaks, coz the original code is returning milliseconds. Here you go:
var d = firstDayOfWeek(9, 2013);
console.log(d.format("yyyy-MM-dd"));
////////////////////////////// Main Code //////////////////////////////
function firstDayOfWeek(week, year) {
if (typeof year !== 'undefined') {
year = (new Date()).getFullYear();
}
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = date.getTime() + weekTime - 86400000;
var result = new Date(targetTime)
return result;
}
function weeksToMilliseconds(weeks) {
return 1000 * 60 * 60 * 24 * 7 * (weeks - 1);
}
function firstWeekOfYear(year) {
var date = new Date();
date = firstDayOfYear(date,year);
date = firstWeekday(date);
return date;
}
function firstDayOfYear(date, year) {
date.setYear(year);
date.setDate(1);
date.setMonth(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
function firstWeekday(date) {
var day = date.getDay(),
day = (day === 0) ? 7 : day;
if (day > 3) {
var remaining = 8 - day,
target = remaining + 1;
date.setDate(target);
}
return date;
}
Take a look at this fiddle. First, it gets the first week of the specified year. This takes into account that according to ISO 8601 the first week of the year is the first week containing a wednesday. Then it adds the weeks to the acquired date and returns the result.
function firstDayOfWeek(week, year) {
var date = firstWeekOfYear(year),
weekTime = weeksToMilliseconds(week),
targetTime = weekTime + date.getTime();
return date.setTime(targetTime);
}

Get Weeks In Month Through Javascript

In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.
I need this to be able to know how many rows I need for a given month.
To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).
So, for something like this, I would want to know it has 5 weeks:
S M T W R F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Thanks for all the help.
Weeks start on Sunday
This ought to work even when February doesn't start on Sunday.
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start on Monday
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start another day
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
None of the solutions proposed here don't works correctly, so I wrote my own variant and it works for any cases.
Simple and working solution:
/**
* Returns count of weeks for year and month
*
* #param {Number} year - full year (2016)
* #param {Number} month_number - month_number is in the range 1..12
* #returns {number}
*/
var weeksCount = function(year, month_number) {
var firstOfMonth = new Date(year, month_number - 1, 1);
var day = firstOfMonth.getDay() || 6;
day = day === 1 ? 0 : day;
if (day) { day-- }
var diff = 7 - day;
var lastOfMonth = new Date(year, month_number, 0);
var lastDate = lastOfMonth.getDate();
if (lastOfMonth.getDay() === 1) {
diff--;
}
var result = Math.ceil((lastDate - diff) / 7);
return result + 1;
};
you can try it here
This is very simple two line code. and i have tested 100%.
Date.prototype.getWeekOfMonth = function () {
var firstDay = new Date(this.setDate(1)).getDay();
var totalDays = new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
return Math.ceil((firstDay + totalDays) / 7);
}
How to use
var totalWeeks = new Date().getWeekOfMonth();
console.log('Total Weeks in the Month are : + totalWeeks );
You'll have to calculate it.
You can do something like
var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on
var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday
Now we just need to genericize it.
var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ];
function GetNumWeeks(month, year)
{
var firstDay = new Date(year, month, 1).getDay();
var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks
// TODO: account for leap years
return baseWeeks + (firstDay >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day.
}
Note: When calling, remember that months are zero indexed in javascript (i.e. January == 0).
function weeksinMonth(m, y){
y= y || new Date().getFullYear();
var d= new Date(y, m, 0);
return Math.floor((d.getDate()- 1)/7)+ 1;
}
alert(weeksinMonth(3))
// the month range for this method is 1 (january)-12(december)
The most easy to understand way is
<div id="demo"></div>
<script type="text/javascript">
function numberOfDays(year, month)
{
var d = new Date(year, month, 0);
return d.getDate();
}
function getMonthWeeks(year, month_number)
{
var $num_of_days = numberOfDays(year, month_number)
, $num_of_weeks = 0
, $start_day_of_week = 0;
for(i=1; i<=$num_of_days; i++)
{
var $day_of_week = new Date(year, month_number, i).getDay();
if($day_of_week==$start_day_of_week)
{
$num_of_weeks++;
}
}
return $num_of_weeks;
}
var d = new Date()
, m = d.getMonth()
, y = d.getFullYear();
document.getElementById('demo').innerHTML = getMonthWeeks(y, m);
</script>
using moment js
function getWeeksInMonth(year, month){
var monthStart = moment().year(year).month(month).date(1);
var monthEnd = moment().year(year).month(month).endOf('month');
var numDaysInMonth = moment().year(year).month(month).endOf('month').date();
//calculate weeks in given month
var weeks = Math.ceil((numDaysInMonth + monthStart.day()) / 7);
var weekRange = [];
var weekStart = moment().year(year).month(month).date(1);
var i=0;
while(i<weeks){
var weekEnd = moment(weekStart);
if(weekEnd.endOf('week').date() <= numDaysInMonth && weekEnd.month() == month) {
weekEnd = weekEnd.endOf('week').format('LL');
}else{
weekEnd = moment(monthEnd);
weekEnd = weekEnd.format('LL')
}
weekRange.push({
'weekStart': weekStart.format('LL'),
'weekEnd': weekEnd
});
weekStart = weekStart.weekday(7);
i++;
}
return weekRange;
} console.log(getWeeksInMonth(2016, 7))
ES6 variant, using consistent zero-based months index. Tested for years from 2015 to 2025.
/**
* Returns number of weeks
*
* #param {Number} year - full year (2018)
* #param {Number} month - zero-based month index (0-11)
* #param {Boolean} fromMonday - false if weeks start from Sunday, true - from Monday.
* #returns {number}
*/
const weeksInMonth = (year, month, fromMonday = false) => {
const first = new Date(year, month, 1);
const last = new Date(year, month + 1, 0);
let dayOfWeek = first.getDay();
if (fromMonday && dayOfWeek === 0) dayOfWeek = 7;
let days = dayOfWeek + last.getDate();
if (fromMonday) days -= 1;
return Math.ceil(days / 7);
}
You could use my time.js library. Here's the weeksInMonth function:
// http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67
weeksInMonth: function(){
var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
},
It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.
This works for me,
function(d){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((d.getDate() + (firstDay - 1))/7);
}
"d" should be the date.
A little rudimentary, yet should cater for original post :
/**
* #param {date} 2020-01-30
* #return {int} count
*/
this.numberOfCalendarWeekLines = date => {
// get total
let lastDayOfMonth = new Date( new Date( date ).getFullYear(), new Date( date ).getMonth() + 1, 0 );
let manyDaysInMonth = lastDayOfMonth.getDate();
// itterate through month - from 1st
// count calender week lines by occurance
// of a Saturday ( s m t w t f s )
let countCalendarWeekLines = 0;
for ( let i = 1; i <= manyDaysInMonth; i++ ) {
if ( new Date( new Date( date ).setDate( i ) ).getDay() === 6 ) countCalendarWeekLines++;
}
// days after last occurance of Saturday
// leaked onto new line?
if ( lastDayOfMonth.getDay() < 6 ) countCalendarWeekLines++;
return countCalendarWeekLines;
};
Thanks to Ed Poor for his solution, this is the same as Date prototype.
Date.prototype.countWeeksOfMonth = function() {
var year = this.getFullYear();
var month_number = this.getMonth();
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
So you can use it like
var weeksInCurrentMonth = new Date().countWeeksOfMonth();
var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6
function getWeeksInMonth(month_number, year) {
console.log("year - "+year+" month - "+month_number+1);
var day = 0;
var firstOfMonth = new Date(year, month_number, 1);
var lastOfMonth = new Date(year, parseInt(month_number)+1, 0);
if (firstOfMonth.getDay() == 0) {
day = 2;
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
} else if (firstOfMonth.getDay() != 1) {
day = 9-(firstOfMonth.getDay());
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
}
var days = (lastOfMonth.getDate() - firstOfMonth.getDate())+1
return Math.ceil( days / 7);
}
It worked for me. Please try
Thanks all
This piece of code give you the exact number of weeks in a given month:
Date.prototype.getMonthWeek = function(monthAdjustement)
{
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
var returnMessage = (Math.ceil(this.getDate()/7) + Math.floor(((7-firstDay)/7)));
return returnMessage;
}
The monthAdjustement variable adds or substract the month that you are currently in
I use it in a calendar project in JS and the equivalent in Objective-C and it works well
function weekCount(year, month_number, day_start) {
// month_number is in the range 1..12
// day_start is in the range 0..6 (where Sun=0, Mon=1, ... Sat=6)
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var dayOffset = (firstOfMonth.getDay() - day_start + 7) % 7;
var used = dayOffset + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
I know this is coming late, I have seen codes upon codes trying to get the number of weeks a particular month falls on, but many have not been really precise but most have been really informative and reusable, I'm not an expert programmer but I can really think and thanks to some codes by some people I was able to arrive at a conclusion.
function convertDate(date) {//i lost the guy who owns this code lol
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
//this line of code from https://stackoverflow.com/a/4028614/2540911
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var myDate = new Date('2019-03-2');
//var myDate = new Date(); //or todays date
var c = convertDate(myDate).split("-");
let yr = c[0], mth = c[1], dy = c[2];
weekCount(yr, mth, dy)
//Ahh yes, this line of code is from Natim Up there, incredible work, https://stackoverflow.com/a/2485172/2540911
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
console.log(weekNumber);
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var first = firstOfMonth.getDate();
//initialize first week
let weekNumber = 1;
while(first-1 < numberOfDaysInMonth){
// add a day
firstOfMonth = firstOfMonth.setDate(firstOfMonth.getDate() + 1);//this line of code from https://stackoverflow.com/a/9989458/2540911
if(days[firstOfMonth.getDay()] === "Sunday"){//get new week every new sunday according the local date format
//get newWeek
weekNumber++;
}
if(weekNumber === 3 && days[firstOfMonth.getDay()] === "Friday")
alert(firstOfMonth);
first++
}
}
I needed this code to generate a schedule or event scheduler for a church on every 3rd friday of a new month, so you can modify this to suit your or just pick your specific date, not "friday and specify the week of the month and Voila!! here you go
None of the solutions here really worked for me. Here is my crack at it.
// Example
// weeksOfMonth(2019, 9) // October
// Result: 5
weeksOfMonth (year, monthIndex) {
const d = new Date(year, monthIndex+ 1, 0)
const adjustedDate = d.getDate() + d.getDay()
return Math.ceil(adjustedDate / 7)
}
Every solutions helped but nothing was working for me so I did my own with moment library :
const getWeeksInAMonth = (currentDate: string) => {
const startOfMonth = moment(currentDate).startOf("month")
const endOfMonth = moment(currentDate).endOf("month")
return moment(endOfMonth).week() - moment(startOfMonth).week() + 1
}

Categories