1

I want to get the previous saturday's date based on today's date, so if we are on tuesday, the date wanted would be 3 days ago. Also, if today is saturday then this will be counted as the previous saturday.

for example:

today = Tuesday 09, July 2019
previous saturday => Saturday, 06 July 2019
next friday => Friday, 12 July

And if today is Saturday then :

today = Saturday, 13 July 2019
previous saturday = Saturday, 13 July 2019
next friday = Friday, 20 July 2019

following Niet's answer here's my code but i'm still getting the wrong dates:

var dateObj = new Date() // friday July 19
dateObj.setDate(dateObj.getDate() - (6-dateObj.getDay())) // gives me thursday, 18 July
dateObj.setDate(dateObj.getDate() + 6) // gives me wednesday, 24 July
hamdi islam
  • 1,327
  • 14
  • 26

1 Answers1

5

You have the convenience that when you call getDay() on a Date object, Saturday is the last entry in the list at 6 (Sunday is 0). This means that the number of days you need to go backwards to get the "most recent" Saturday is just 6-dateObj.getDay()

Take this and combine it with the fact that JS will "auto-correct" dates such that the "negative 1st of July" is the 29th of June, and you can just call

dateObj.setDate(dateObj.getDate() - (6-dateObj.getDay()))

Now dateObj is the most recent Saturday, as desired.

The following Friday can then be obtained similarly:

dateObj.setDate(dateObj.getDate() + 6)

dateObj is now the Friday after the most recent Saturday.


I got the numbers wrong. It's:

dateObj.setDate(dateObj.getDate() - (dateObj.getDay()+1)%7);

As a more general case, you could actually just map dateObj.getDay() to a number of days to go back. The math in the previous code block is equivalent to:

const map = [1, 2, 3, 4, 5, 6, 0];
dateObj.setDate(dateObj.getDate() - map[dateObj.getDay()]);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • hello, thank you for your answer, i'm still getting the wrong dates please have a look at my edited post i've included my code – hamdi islam Jul 19 '19 at 15:07
  • thank you very much I really appreciate it, can you please explain the part where you used " dateObj.getDay()+1)%7 ". Thank you again – hamdi islam Jul 19 '19 at 23:52