Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the most recently occurring Sunday

Tags:

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?

like image 211
Andrew Shepherd Avatar asked Oct 09 '12 00:10

Andrew Shepherd


People also ask

How to get previous Sunday to the current Date?

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.

How to get last Sunday Date in JavaScript?

getTime() + (24*60*60*1000)*n); } var today = new Date(now. getFullYear(), now. getMonth(), now. getDate()); var lastSunday = today.

How do I get this week in Javascript?

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.

How do I display current week in HTML?

HTML input type="week"


1 Answers

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

Edit

The original answer had an incorrect version adding time, that does add one day but not how the OP wants.

like image 168
RobG Avatar answered Nov 14 '22 14:11

RobG