I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?
-
If every little bit of speed is crucial, you may want to performance test my answer. I'm getting a little better performance with mine in browsers (except for IE, which favors CMS). Of course, you would need to test it with MongoDB. When the function gets passed a date that is Monday, it should be even faster, since it just returns the unmodified original date. – user113716 Nov 11 '10 at 17:06
-
I got the same problem and because javascript date object have a lot of bugs I'm using now http://www.datejs.com (here http://code.google.com/p/datejs/), a library that correct the miss behavior of the native date. – lolol Oct 02 '12 at 20:46
-
The question title asks for the first day of the week while the question description asks for the date of the last Monday. These are actually two different questions. Check my answer that solves them both in a correct manner. – Louis Ameline Aug 19 '18 at 14:08
17 Answers
Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
You can then subtract that number of days plus one, for example:
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
getMonday(new Date()); // Mon Nov 08 2010
- 522
- 4
- 18
- 769,263
- 179
- 909
- 832
-
3Does this function has a bug? - if the date in question is Thursday the 2nd, day = 4, diff = 2 - 4 + 1 = -1, and the result of setDate will be 'the day before the last day of the previous month' (see [this](http://www.w3schools.com/jsref/jsref_setdate.asp)). – Izhaki May 24 '13 at 12:11
-
3@Izhaki what do you mean? For May 2 the function returns April 29, which is correct. – meze Jul 26 '13 at 07:22
-
21If Sunday is the first day of the week, use: `diff = d.getDate() - day;` – cfree Sep 18 '14 at 21:41
-
Using BeanShell the following code worked for me: `Date date = new Date(); int dayIndex = date.getDay(); // 0 = Sunday, 1 = Monday ... int diff = dayIndex - (dayIndex == 0? -6 : 1); date.setDate(date.getDate()-diff); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); String formattedDate = df.format(date); vars.put("dateOfLastMonday",formattedDate);` – Ishtiaque Hussain Jul 29 '15 at 17:49
-
It didn't work for me when the previous Monday of the date belongs to another month for example `d = '2016-01-1'` it returns `"monday": "2015-12-27T06:00:00.000Z"` which is wrong because it must return `2015-12-28` – alexventuraio Jan 12 '16 at 01:41
-
3Thanks for the code @SMS . I made a little twist for getting exactly 0 hours of the first day of week. `d.setHours(0); d.setMinutes(0); d.setSeconds(0);` – Awi May 22 '16 at 21:27
-
You may want to check my answer which takes the first day of week as second parameter. – Louis Ameline Aug 20 '18 at 22:03
-
-
4
-
`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)); }` seems better, `setDate` return a Date? – XiaoChi Jul 28 '19 at 06:15
-
1@Ayyash hence the clone at the begining. But the last `new Date` is useless: `d.setDate(diff); return d;` is enough – Erdal G. Jul 17 '20 at 15:28
Not sure how it compares for performance, but this works.
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
Or as a function:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
- 11,447
- 3
- 32
- 46
- 310,407
- 61
- 442
- 435
-
6This should have been the answer, its the only one that answers the question asked. The others are buggy or refer you to third party libraries. – OverMars Mar 07 '15 at 23:12
-
Cool it works for me! By making some adjustments I cool get both, Monday and Friday of the week from a given date! – alexventuraio Jan 12 '16 at 16:37
-
10This is great except this function should be called "setToMonday" as it modifies the date object passed in. getMonday, would return a new Date that is the monday based on the date passed in. A subtle difference, but one that caught me after using this function. Easiest fix is to put `date = new Date(date);` as the first line in the getMonday function. – Shane Dec 08 '16 at 23:52
-
This is awesome. A getSunday method is even easier! Thanks a bunch! – JesusIsMyDriver.dll Oct 26 '17 at 19:00
-
6This answer is wrong because not all days have 24h because of daytime savings. It may either change the hour of your date unexpectedly or even return the wrong day at certain occasions. – Louis Ameline Aug 19 '18 at 13:35
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that add/subtract hours/minutes/seconds/milliseconds are wrong because not all days have 24 hours.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
- 2,599
- 1
- 21
- 25
-
For those who are searching for lastDayofTheWeek https://jsfiddle.net/codeandcloud/5ct8odqr/ – naveen Apr 22 '22 at 15:14
-
1
-
I need it for MongoDB database. So i can't reference date.js, but thank you for your code snippet. – INs Nov 11 '10 at 16:18
-
1Ah, I wasn't aware you could execute JS directly in MongoDB. That's pretty slick. Had assumed you were using the JS to prepare the query data. – Matt Nov 11 '10 at 16:32
-
Like jQuery, not interested in pulling down an entire library (no matter how small) to get access to one simple function. – The Muffin Man Sep 06 '17 at 19:29
-
Not a good solution, because there are countries, their first day of the week is sunday. – Stefan Brendle Jan 17 '20 at 08:01
First / Last Day of The Week
To get the upcoming first day of the week, you can use something like so:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const dayOfTheWeek = date.getDay();
const newDate = date.setDate(today - dayOfTheWeek + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
Or to get the latest first day:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const dayOfTheWeek = date.getDay();
const newDate = date.setDate(today - (dayOfTheWeek || 7));
return new Date(newDate);
}
console.log(getLastSunday());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* You can also format it using toISOString method like so: getLastSunday().toISOString()
- 17,742
- 16
- 75
- 90
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
- 4,800
- 3
- 26
- 31
- 121
- 1
- 4
I'm using this
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
- 1,554
- 1
- 20
- 30
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
- 2,064
- 2
- 19
- 26
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
- 1,515
- 1
- 10
- 8
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
- 1,472
- 1
- 15
- 13
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
- 11
- 3
An example of the mathematically only calculation, without any Date functions.
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
- 542
- 1
- 5
- 11
-
This answer assumes that the date is in a specific part of the week. It might give you the last Thursday! Instead of %-ing to a half-week offset the calculation: `ts=+ts+60*60*24*1000 * 3; return new Date((ts - ts % (60 * 60 * 24 * 7 * 1000))-60*60*24*1000 * 3)` – Simon May 04 '22 at 08:09
a more generalized version of this... this will give you any day in the current week based on what day you specify.
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
- 93
- 1
- 11
-
@mate.gvo Care to explain what is not working for you? It works fine for me. – anastymous Jul 21 '21 at 23:35
Returns Monday 00am to Monday 00am.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
- 521
- 6
- 12
Simple solution for getting the first day of the week.
With this solution, it is possible to set an arbitrary start of week (e.g. Sunday = 0, Monday = 1, Tuesday = 2, etc.).
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
- The solution correctly wraps on months (due to
Date.setDate()being used) - For
startOfWeek, the same constant numbers as inDate.getDay()can be used
- 917
- 1
- 10
- 19
I use this:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
It works fine.
- 1,295
- 1
- 15
- 30
Check out: moment.js
Example:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Bonus: works with node.js too
- 17,460
- 12
- 88
- 107
-
19That's not an answer to OP's question though. He has a date, say 08/07/14 (d/m/y). He wants to get the first day of this week (for my locale this would be the Monday that has just passed, or yesterday) An answer to his question with moment would be `moment().startOf('week')` – Jeroen Pelgrims Jul 08 '14 at 13:51
-
2Note that `moment().startOf("week")` might give the date of the previous Sunday, depending on locale settings. In that case, use `moment().startOf('isoWeek')` instead: https://runkit.com/embed/wdpi4bjwh6rt – Harm Apr 07 '19 at 11:33
-
PS Docs on `startOf()`: https://momentjs.com/docs/#/manipulating/start-of/ – Harm Apr 07 '19 at 11:43