Get next day, skip weekends - javascript

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

Related

How to get a specify date in every month in Javascript?

I need to find this month, previous month and the next month of a specific date.
For example, date was set to 31 of every month, what I expect to get the date is
2018-02-28, 2018-03-31 and 2018-04-30. For those dates which has no 31, than it becomes the day before.
And finally generate 2 period, 2018-02-28 to 2018-03-29, 2018-03-30 to 2018-04-31.
I don't know how to handle feb and the month which less than 31.
var d = new Date();
var tyear = d.getFullYear(); //2018
var tmonth = d.getMonth(); //2
new Date(2018, tmonth-1, 31);//output 2018-03-02 not what I wanted
A simple algorithm is to add months to the original date, and if the new date is wrong, set it to the last day of the previous month. Keeping the original date values unmodified helps, e.g.
/* #param {Date} start - date to start
** #param {number} count - number of months to generate dates for
** #returns {Array} monthly Dates from start for count months
*/
function getMonthlyDates(start, count) {
var result = [];
var temp;
var year = start.getFullYear();
var month = start.getMonth();
var startDay = start.getDate();
for (var i=0; i<count; i++) {
temp = new Date(year, month + i, startDay);
if (temp.getDate() != startDay) temp.setDate(0);
result.push(temp);
}
return result;
}
// Start on 31 Jan in leap year
getMonthlyDates(new Date(2016,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 31 Jan not in leap year
getMonthlyDates(new Date(2018,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 30 Jan
getMonthlyDates(new Date(2018,0,30), 4).forEach(d => console.log(d.toString()));
// Start on 5 Jan
getMonthlyDates(new Date(2018,0,5), 4).forEach(d => console.log(d.toString()));
I think you're going to need an array with 12 numbers in it. Each number is the amount of days in each month and the numbers in the array go in order (first number is 31 because January has 31 days, second is 28 or 29 for Feb), etc. Then you'll get the month number from your input date and look in the array at the number corresponding to the month number +/- 1.
You'll then need to construct a date for the previous month and the next month based on the number of days in the current month.
See comments inline:
let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
document.getElementById("date").addEventListener("input", function(){
console.clear();
// Create new Date based on value in date picker
var selectedDate = new Date(this.value + 'T00:00');
var year = selectedDate.getYear();
// Determine if it is a leap year (Feb has 29 days) and update array if so.
if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
daysInMonths[1] = 29;
}
var selectedDateMonth = selectedDate.getMonth();
// Get previous month number (if current month is January, get December)
let prevMonth = selectedDateMonth > 0 ? selectedDateMonth - 1 : 11;
let prevMonthDate = null;
// If selected date is last day of month...
if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
// Create new date that takes the selected date and subtracts the correct amount of
// days from it based on a lookup in the array.
var newDate1 = new Date(selectedDate.getTime());
prevMonthDate =
new Date(newDate1.setDate(selectedDate.getDate() - daysInMonths[selectedDateMonth]));
} else {
// Create a new date that is last month and one day earlier
var newDate2 = new Date(selectedDate.getTime());
prevMonthDate =
new Date(new Date(newDate2.setDate(selectedDate.getDate() - 1))
.setMonth(selectedDate.getMonth() - 1));
}
// Get next month (if current month is December, get January
let nextMonth = selectedDateMonth < 11 ? selectedDateMonth + 1 : 0;
let nextMonthDate = null;
// Same idea for next month, but add instead of subtract.
// If selected date is last day of month...
if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
var newDate3 = new Date(selectedDate.getTime());
nextMonthDate =
new Date(newDate3.setDate(selectedDate.getDate() + daysInMonths[selectedDateMonth + 1]));
} else {
var newDate4 = new Date(selectedDate.getTime());
nextMonthDate = new Date(new Date(newDate4.setDate(selectedDate.getDate() + 1)).setMonth(selectedDate.getMonth() + 1));
}
console.log("Last month date: " + prevMonthDate.toLocaleDateString());
console.log("Next month date: " + nextMonthDate.toLocaleDateString());
});
<p>Pick a date: <input type="date" id="date"></p>
Use this approach:
Javascript Date Object – Adding and Subtracting Months
From the Author
There is a slight problem with the Javascript Date() Object when trying to advance to the next month or go back to the previous month.
For example, if your date is set to October 31, 2018 and you add one month, you'd probably expect the new date to be November 30, 2018 because November 31st doesn't exist. This, however, isn't the case.
Javascript automatically advances your Date object to December 1st. This functionality is very useful in most situations(i.e. adding days to a date, determining the number of days in a month or if it's a leap year), but not for adding/subtracting months. I've put together some functions below that extend the Date() object: nextMonth() and prevMonth().
function prevMonth() {
var thisMonth = this.getMonth();
this.setMonth(thisMonth - 1);
if (this.getMonth() != thisMonth - 1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
this.setDate(0);
}
function nextMonth() {
var thisMonth = this.getMonth();
this.setMonth(thisMonth + 1);
if (this.getMonth() != thisMonth + 1 && this.getMonth() != 0)
this.setDate(0);
}
Date.prototype.nextMonth = nextMonth;
Date.prototype.prevMonth = prevMonth;
var today = new Date(2018, 2, 31); //<----- March 31st, 2018
var prevMonth = new Date(today.getTime());
prevMonth.prevMonth();
console.log("Previous month:", prevMonth);
console.log("This month:", today)
var nextMonth = new Date(today.getTime());
nextMonth.nextMonth();
console.log("Next month:", nextMonth);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Dates and time zones are a real pain in JS, so challenge accepted.
I broke it down in two steps:
- Count the days of prev and next month
- Compare with selected day and pick the lowest number
Testcases included
function createUTCDate(year, month, day) {
return new Date(Date.UTC(year, month, day));
}
function splitDate(date) {
return {
year: date.getUTCFullYear(),
month: date.getUTCMonth(),
day: date.getUTCDate()
};
}
function numberOfDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
function dateNextMonth(dateObj) {
const daysNextMonth = numberOfDaysInMonth(dateObj.year, dateObj.month + 1);
const day = Math.min(daysNextMonth, dateObj.day);
return createUTCDate(dateObj.year, dateObj.month + 1, day);
}
function datePreviousMonth(dateObj) {
const daysPrevMonth = numberOfDaysInMonth(dateObj.year, dateObj.month - 1);
const day = Math.min(daysPrevMonth, dateObj.day);
return createUTCDate(dateObj.year, dateObj.month - 1, day);
}
const log = console.log;
function print(dateString) {
const date = new Date(dateString);
const dateObj = splitDate(date);
log("Previous: ", datePreviousMonth(dateObj).toISOString());
log("Selected: ", date.toISOString());
log("Next: ", dateNextMonth(dateObj).toISOString());
log("--------------");
}
const testCases = [
"2018-03-01 UTC",
"2018-03-31 UTC",
"2018-01-01 UTC",
"2018-12-31 UTC"
];
testCases.forEach(print);
Please note that the hack with new Date(xxx + " UTC") is not according to spec and is just there for testing purposes. Results may vary per browser.
You should choose an input format and construct your dates accordingly.
I handle it in a foolish way by concatenating string
let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var target = nexttarget = lasttarget = "29"; //target day
if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
daysInMonths[1] = 29;
}
function findLastDay(target, month){
if(target > daysInMonths[month]){
target = daysInMonths[month];
}
return target;
}
then
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
target = findLastDay(target, month);
var this_month = year+"-"+months[month]+"-"+target;
console.log(this_month);//2018-03-29
// next month
if(month == 11){
nextmonth = 0;
nextyear = year + 1;
}else{
nextmonth = month+1;
nextyear = year;
}
nexttarget = findLastDay(nexttarget, nextmonth);
var next_month = nextyear+"-"+months[nextmonth]+"-"+nexttarget;
console.log(next_month);//2018-04-29
//last month
if(month == 0){
lastmonth = 11;
lastyear = year - 1;
}else{
lastmonth = month - 1;
lastyear = year;
}
lasttarget = findLastDay(lasttarget, lastmonth);
var last_month = lastyear+"-"+months[lastmonth]+"-"+lasttarget;
console.log(last_month);//2018-02-28
Date handling is tricky at the best of times. Don't do this yourself. Use Moment.js.
var target = 31;
var today = moment().date(target).calendar();
// today == '03/31/2018'
var nextMonth = moment().date(target).add(1, 'month').calendar();
// nextMonth == '04/30/2018'
var lastMonth = moment().date(target).subtract(1, 'month').calendar()
// lastMonth == '02/28/2018'

group by weeks,days and year javascript [duplicate]

I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
Making it work with first and last days in different months is left as an exercise for the user
Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)
Another popular alternative is date-fns.
You can also use following lines of code to get first and last date of the week:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Hope it will be useful..
The excellent (and immutable) date-fns library handles this most concisely:
const start = startOfWeek(date);
const end = endOfWeek(date);
Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:
const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});
Here's a quick way to get first and last day, for any start day.
knowing that:
1 day = 86,400,000 milliseconds.
JS dates values are in milliseconds
Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day
Small change to #Chris Lang answer.
if you want Monday as the first day use this.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Thaks #Chris Lang
This works across year and month changes.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You could do something like this
var today = new Date();
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);
Where startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).
SetDate will sets the day of the month. Using setDate during start and end of the month,will result in wrong week
var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014
If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014
So overcome this issue i used
var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week
I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.
Simply to get current date time in specific format
case 'Today':
moment().format("DD/MM/YYYY h:mm A");
case 'This Week':
moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");
Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.
case 'This Month':
moment().endOf('month').format("DD/MM/YYYY h:mm A");
case 'This Quarter':
moment().endOf('quarter').format("DD/MM/YYYY h:mm A");
I chose this format as per my need. You can change the format according to your requirement.
//get start of week; QT
function _getStartOfWeek (date){
var iDayOfWeek = date.getDay();
var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ? -6:1);
return new Date(date.setDate(iDifference));
},
function _getEndOfWeek(date){
return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
},
*current date == 30.06.2016 and monday is the first day in week.
It also works for different months and years.
Tested with qunit suite:
QUnit.module("Planung: Start of week");
QUnit.test("Should return start of week based on current date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date());
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a sunday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a monday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.module("Planung: End of week");
QUnit.test("Should return end of week based on current date", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date());
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on monday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
var dt = new Date() //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));
This will be useful for any date scenario.
Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
function getFirstDayOfWeek(date, from) {
//Default start week from 'Sunday'. You can change it yourself.
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 7 : start);
d.setDate(diff);
return d;
};
Last day of week is just 6 days after first day of week
function getLastDayOfWeek(date, from) {
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
d.setDate(diff);
return d;
};
Test:
getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017
The biggest issue when the given date's week is in-between two months. (Like 2022-07-01, it's the 5th day of the week.)
Using getDay function we check if the week is in-between months.
Note: getDay() function identifies week start day as sunday, so it'll return 0 for sunday.
var curr = new Date(); // get current date
var weekdaynum = curr.getDay();
if(weekdaynum == 0){ //to change sunday to the last day of the week
weekdaynum = 6;
} else{
weekdaynum = weekdaynum-1;
}
var firstweek = curr.getDate() - weekdaynum;
var lastweek = firstweek + 6; // last day is the first day + 6
if((curr.getDate()-weekdaynum) <= 0){
var firstweek_lasmonth_lastdate = new Date(currweek.getFullYear(),currweek.getMonth(), 0);
var firstweek_diff = firstweek_lasmonth_lastdate.getDate()-Math.abs(firstweek);
var firstweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff);
var lastweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff+7);
} else{
var firstweekday = new Date(curr.setDate(firstweek));
var lastweekday = new Date(curr.setDate(lastweek));
}
So this will return (given date is: 2022/07/01):
firstweekday = Mon Jun 27 2022 00:00:00
lastweekday = Sun Jul 03 2022 00:00:00
Hope this helps.
krtek's method has some wrong,I tested this
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);
it works
Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;
JavaScript
function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
var cd = curr.getDate() - curr.getDay();
var from = new Date(curr.setDate(cd + firstDay));
var to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
TypeScript
export enum WEEK_DAYS {
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
export const getWeekDays = (
curr: Date,
firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
const cd = curr.getDate() - curr.getDay();
const from = new Date(curr.setDate(cd + firstDay));
const to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) ) // Mon Nov 08 2010
Pure vanilla JS. no third party libraries.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
^ this returns Sunday 00am to Sunday 00am. Adjust the "7" to get what you want.
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 6)).toUTCString();
console.log("firstday", firstday);
console.log("lastday", lastday);
Works with different months and years.
let wDate = new Date();
let dDay = wDate.getDay() > 0 ? wDate.getDay() : 7;
let first = wDate.getDate() - dDay + 1;
let firstDayWeek = new Date(wDate.setDate(first));
let lastDayWeek = new Date(wDate.setDate(firstDayWeek.getDate()+6));
console.log(firstDayWeek.toLocaleDateString());
console.log(lastDayWeek.toLocaleDateString());
Nice suggestion but you got a small problem in lastday.
You should change it to:
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.
let startOfWeek = moment().startOf("isoWeek").toDate();
let endOfWeek = moment().endOf("isoWeek").toDate();
We have added jquery code that shows the current week of days from monday to sunday.
var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
let first = d.getDate() - d.getDay() + i;
let dt = new Date(d.setDate(first));
var _day = _days[dt.getDay()];
var _month = _months[dt.getMonth()];
var _date = dt.getDate();
if(_date < 10 ){
_date = '0' +_date;
}
var _year = dt.getFullYear();
var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
week.push(fulldate);
}
console.log(week);
An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit
// For start of week, accepts any day as start
function startOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(d);
e.setHours(23,59,59,999);
// Define methods
let start = {
second: d => d.setMilliseconds(0),
minute: d => d.setSeconds(0,0),
hour : d => d.setMinutes(0,0,0),
day : d => d.setHours(0,0,0,0),
week : d => {
start.day(d);
d.setDate(d.getDate() - d.getDay() + weekStartDay);
if (d > e) d.setDate(d.getDate() - 7);
},
month : d => {
start.day(d);
d.setDate(1);
},
year : d => {
start.day(d);
d.setMonth(0, 1);
},
decade: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 10);
},
century: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 100);
},
millenium: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 1000);
}
}
start[unit](d);
return d;
}
// Returns a new Date object set to end of given unit
// For end of week, accepts any day as start day
// Requires startOf
function endOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(date);
e.setHours(23,59,59,999);
// Define methods
let end = {
second: d => d.setMilliseconds(999),
minute: d => d.setSeconds(59,999),
hour : d => d.setMinutes(59,59,999),
day : d => d.setHours(23,59,59,999),
week : w => {
w = startOf('week', w, weekStartDay);
w.setDate(w.getDate() + 6);
end.day(w);
d = w;
},
month : d => {
d.setMonth(d.getMonth() + 1, 0);
end.day(d);
},
year : d => {
d.setMonth(11, 31);
end.day(d);
},
decade: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 10 + 9);
},
century: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 100 + 99);
},
millenium: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 1000 + 999);
}
}
end[unit](d);
return d;
}
// Examples
let d = new Date();
['second','minute','hour','day','week','month','year',
'decade','century','millenium'].forEach(unit => {
console.log(('Start of ' + unit).padEnd(18) + ': ' +
startOf(unit, d).toString());
console.log(('End of ' + unit).padEnd(18) + ': ' +
endOf(unit, d).toString());
});
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.
if i remove .toUTCString(). output which i receive is not as expected
Small change to #SHIVA's answer which is a changed #Chris Lang answer.
For monday first usage with fix when today is sunday.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return new Date(this.setDate(this.getDate() - (this.getDay() == 0 ? 7 : this.getDay()) + 7));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You can try the below one too
let weekBgnDt = new Date();
let weekEndDt = new Date();
let wBeginDateLng, wEndDateLng, diffDays,dateCols=[];
if (weekBgnDt.getDay() > 0) {
diffDays = 0 - weekBgnDt.getDay();
weekBgnDt.setDate(weekBgnDt.getDate() + diffDays)
}
weekEndDt = weekEndDt.setDate(weekBgnDt.getDate() + 6)
wBeginDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(weekBgnDt);
wEndDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', month:
'2-digit' }).format(weekEndDt);
wBeginDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekBgnDt);
wEndDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekEndDt);
console.log(wBeginDate, "-", wBeginDateLng)
console.log(wEndDate, "-", wEndDateLng)
for(let i=weekBgnDt;i<=weekEndDt;){
dateCols.push(new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(i));
i=weekBgnDt.setDate(weekBgnDt.getDate()+1)
}
console.log({wBeginDate,wBeginDateLng,wEndDate,wEndDateLng,dateCols})
The result will be printed as
{ wBeginDate: "16/05/2021", wBeginDateLng: "16 May 2021", wEndDate: "22/05/2021", wEndDateLng: "22 May 2021", dateCols: Array ["16/05/2021", "17/05/2021", "18/05/2021", "19/05/2021", "20/05/2021", "21/05/2021", "22/05/2021"] }
The right way to get the first and last date of the current week with appropriate month & year is as below
const curr = new Date();
const first = curr.getDate() - curr.getDay() + 1; // Start from Monday
const firstDate = new Date(curr.setDate(first));
const lastDate = new Date(curr.setDate(firstDate.getDate() + 6));
console.log(firstDate.toLocaleDateString(), lastDate.toLocaleDateString());
You can use this function, it works with first and last day of the week in different months or years
const getFirstAndLastDayOfTheWeek = () => {
// The starting time is the same current
let a = new Date();
let b = new Date();
const weekDay = a.getDay();
if (weekDay === 0) {
a.setDate(a.getDate() - 6);
} else if (weekDay === 1) {
b.setDate(b.getDate() + 7 - b.getDay());
} else if (weekDay >= 1) {
a.setDate(a.getDate() - a.getDay() + 1);
b.setDate(b.getDate() + 7 - b.getDay());
}
return { firstWeekDate: a, lastWeekDate: b };
}
console.log(getFirstAndLastDayOfTheWeek());

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

How can I get the 4 Mondays of a month with js?

I'm building a chart where the x-axis should be the four weeks of a month. I would like to display only the four Mondays of that month.
I already have the currentMonth and the currentYear variables, and I know how to get the first day of the month. All I need is to get the four Mondays of a month in an array. And all of this in the same JavaScript file.
I'm pretty lost within my programming logic, and I've seen plenty of solutions that don't fit my use case.
Right now, I have:
var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear, currentMonth, 1);
var firstWeekDay = firstDayofMonth.getDay();
but I would like to have something like this:
var myDates = [
new Date(firstMonday),
new Date(secondMonday),
new Date(thirdMonday),
new Date(fourthMonday),
];
The following function will return all Mondays for the current month:
function getMondays() {
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
This would return the fourth last monday of month [m] in year [y]
function lastmonday(y,m) {
var dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstmonday = false;
while (currentmonth === m){
firstmonday = dat.getDay() === 1 || firstmonday;
dat.setDate(dat.getDate()+(firstmonday ? 7 : 1));
currentmonth = dat.getMonth()+1;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastmonday(2012,3); //=>Mon Mar 26 2012 00:00:00 GMT+0200
lastmonday(2012,2) //=>Mon Feb 27 2012 00:00:00 GMT+0100
lastmonday(1997,1) //=>Mon Jan 27 1997 00:00:00 GMT+0100
lastmonday(2012,4) //=>Mon Apr 30 2012 00:00:00 GMT+0200
To be more generic, this will deliver the last any weekday of a month:
function lastDayOfMonth(y,m,dy) {
var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}
,dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstday = false;
while (currentmonth === m){
firstday = dat.getDay() === days[dy] || firstday;
dat.setDate(dat.getDate()+(firstday ? 7 : 1));
currentmonth = dat.getMonth()+1 ;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastDayOfMonth(2012,2,'tue'); //=>Tue Feb 28 2012 00:00:00 GMT+0100
lastDayOfMonth(1943,5,'fri'); //=>Fri May 28 1943 00:00:00 GMT+0200
For whoever may need, this is a general function to get every monday, tuesday, etc
getDatesOfDayOfWeek (year, month, dayOfWeek) {
const initialDate = new Date(year, month, 1);
const datesOfDayOfWeek = [];
while (initialDate.getDay() !== dayOfWeek) {
initialDate.setDate(initialDate.getDate() + 1);
}
while (initialDate.getMonth() === month) {
const nextDate = new Date(initialDate.getTime());
datesOfDayOfWeek.push(nextDate.getDate());
initialDate.setDate(initialDate.getDate() + 7);
}
return datesOfDayOfWeek;
}
I took Jake's code and generalized it to get the next N occurrences of a particular schedule. (e.g. "Get me the next 10 instances of 2nd Mondays and 1st and 3rd Wednesdays.")
schedule is an object with keys for day-of-week whose values are
an array of the incident within a month that the DoW falls.
keys can include numbers from 1-5, and -1 for "last."
items in a value array can include numbers from 0-6, where 0 is Sunday.
count is optional (defaults to 6) and represents how many items to show.
Samples
First and third Mondays would be nextNthMdays({1: [1, 3]})
Second Wed and Fri would be nextNthMdays({3: [2], 5: [2]})
Last Thursdays would be nextNthMdays({4: [-1]})
function nextNthMdays(schedule, count) {
var d = new Date(),
month = 999,
nthInMonth,
dates = [];
if (count == undefined) {
count = 6;
}
// start at the beginning of the month
d.setDate(1);
// Iterate until we have enough
while (dates.length < count) {
var day = d.getDay();
// Reset counters each month
if (d.getMonth() !== month) {
month = d.getMonth();
nthInMonth = Object.keys(schedule).reduce(function (obj, x) {
obj[x] = 0;
return obj;
}, {});
}
// When you reach an interesting weekday
if (day in schedule) {
// Increment its counter
nthInMonth[day]++;
// If it's after today
if (d > new Date()) {
// and its counter matches
if (schedule[day].indexOf(nthInMonth[day]) !== -1) {
// Add it
dates.push(new Date(d.getTime()));
}
// or if we want the last one
else if (schedule[day].indexOf(-1) !== -1) {
// verify that 7 days from then is a different month
var sevenAway = new Date(d);
sevenAway.setDate(sevenAway.getDate() + 7);
if (d.getMonth() !== sevenAway.getMonth()) {
// Add it
dates.push(new Date(d.getTime()));
}
}
}
}
// Move on to the next day
d.setDate(d.getDate() + 1);
}
return dates;
}
Demonstration
Expand the snippet to run some examples.
// `schedule` is an object with keys
// for day-of-week whose values are
// an array of the incident within
// a month that the DoW falls.
//
// keys can include numbers from
// 1-5, and -1 for "last."
// items in a value array can include
// numbers from 0-6, where 0 is
// Sunday.
//
// `count` is optional (defaults to 6)
// and represents how many items to
// show.
//
// First and third Mondays would be
// nextNthMdays({1: [1, 3]})
// Second Wed and Fri would be
// nextNthMdays({3: [2], 5: [2]})
// Last Thursdays would be
// nextNthMdays(4: [-1])
function nextNthMdays(schedule, count) {
var d = new Date(),
month = 999,
nthInMonth,
dates = [];
if (count == undefined) {
count = 6;
}
// start at the beginning of the month
d.setDate(1);
// Iterate until we have enough
while (dates.length < count) {
var day = d.getDay();
// Reset counters each month
if (d.getMonth() !== month) {
month = d.getMonth();
nthInMonth = Object.keys(schedule).reduce(function (obj, x) {
obj[x] = 0;
return obj;
}, {});
}
// When you reach an interesting weekday
if (day in schedule) {
// Increment its counter
nthInMonth[day]++;
// If it's after today
if (d > new Date()) {
// and its counter matches
if (schedule[day].indexOf(nthInMonth[day]) !== -1) {
// Add it
dates.push(new Date(d.getTime()));
}
// or if we want the last one
else if (schedule[day].indexOf(-1) !== -1) {
// verify that 7 days from then is a different month
var sevenAway = new Date(d);
sevenAway.setDate(sevenAway.getDate() + 7);
if (d.getMonth() !== sevenAway.getMonth()) {
// Add it
dates.push(new Date(d.getTime()));
}
}
}
}
// Move on to the next day
d.setDate(d.getDate() + 1);
}
return dates;
}
console.log('Next third Wednesdays');
console.log(nextNthMdays({3: [3],}));
console.log('Next first and third Mondays');
console.log(nextNthMdays({1: [1, 3],}, 4));
console.log('Next second Wed/Fridays');
console.log(nextNthMdays({3: [2], 5: [2],}, 3));
console.log('Next "Last Thursdays of the month"');
console.log(nextNthMdays({4: [-1],}, 3));

Get week of year in JavaScript like in PHP

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

Categories