I need to display the current week in a calendar view, starting from Sunday.
What's the safest way to determine "last sunday" in Javascript?
I was calculating it using the following code:
Date.prototype.addDays = function(n) { return new Date(this.getTime() + (24*60*60*1000)*n); } var today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); var lastSunday = today.addDays(0-today.getDay());
This code makes the assumption that every day consists of twenty four hours. This is correct, EXCEPT if it's a daylight savings crossover day, in which case the day could be twenty-three or twenty-five hours.
This week, In Sydney, Australia, we set our clocks forward an hour. As a result, my code calculates lastSunday
as 23:00 on Saturday.
So what IS the safest and most efficient way to determine last Sunday?
To get the date of the previous Sunday, use the setDate() method, setting the date to the result of subtracting the day of the week from the day of the month. The setDate method changes the day of the month of the specific Date instance.
getTime() + (24*60*60*1000)*n); } var today = new Date(now. getFullYear(), now. getMonth(), now. getDate()); var lastSunday = today.
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.
HTML input type="week"
To safely add exactly one day, use:
d.setDate(d.getDate() + 1);
which is daylight saving safe. To set a date object to the last Sunday:
function setToLastSunday(d) { return d.setDate(d.getDate() - d.getDay()); }
Or to return a new Date object for last Sunday:
function getLastSunday(d) { var t = new Date(d); t.setDate(t.getDate() - t.getDay()); return t; }
The original answer had an incorrect version adding time, that does add one day but not how the OP wants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With