How to find sunday 9 weeks ago irrespective of what day of the week today is using JavaScript

82 views Asked by At

Hope someone can help me. I am trying to write a function to find the sunday 9 weeks ago irrespective of what day of the week today is using javascript.
I I tried with moment().day(-56) but its not working. Any other way we can do this?

5

There are 5 answers

0
Tyler Sells On

Is this what you're looking for?

console.log(moment().startOf('week').subtract(9,'weeks').format("MM-DD-yyyy"))

Sunday is the start of the week, so we go there to find a baseline. Then, subtract 9 weeks from there using Momentjs subtract function. Formatted for friendly output.

0
AudioBubble On

As per https://momentjscom.readthedocs.io/en/latest/moment/02-get-set/06-day/ you can get 9 Sundays ago with:

moment().day(-63)
1
Kevin Ashworth On

I think you need to calculate the week and the weekday separately. Try something like this: https://codepen.io/kevinashworth/pen/bGeGjGx

var thisWeek = moment().week()
var theSunday = moment().week(thisWeek - 9).weekday(0).format("dddd, MMMM Do, YYYY")
0
Emmanuel Neni On

I am assuming you need to find the first Sunday 9 weeks ago so maybe the bellow functions help.

const findNineWeeksAgo = () => {
  let nineWeeksAgo = new Date('August 19, 1975 23:15:30')
  const nineWeeksInDays = 63

  // You can modify a date using setDate. It automatically corrects for shifting to new months/years etc.
  nineWeeksAgo.setDate(nineWeeksAgo.getDate() - nineWeeksInDays);

  return nineWeeksAgo
}

const findNextSunday = () => {
  const dateNineWeeksAgo = findNineWeeksAgo()
  // getting the exact day of the week that was 9 weeks ago
  let dayNineWeeksAgoe = dateNineWeeksAgo.getDay()
  // if the exact day is sunday i.e 0 return that date in string format else find number of days to sunday add them to the exact date and reurn that.
  if (dayNineWeeksAgoe === 0) return dayNineWeeksAgoe.toString()
  else {
    let daysLeftToSunday = 7 - dayNineWeeksAgoe
    dateNineWeeksAgo.setDate(dateNineWeeksAgo.getDate() + daysLeftToSunday);
    return dateNineWeeksAgo.toString()
  }
}

console.log(findNextSunday())

0
jmrker On

If you choose to use just native JS, this might suit your needs.

<script>
 var today = new Date();
 // today.getDay() is current day-of-week (0=Sun ... 6=Sat)
 var lastSun9wksAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate()-(9*7+today.getDay()));
 // alter display for 9 weeks ago with day-of-week offset
 alert(lastSun9wksAgo.toDateString());
</script>

Could be put into a two line function if used repeatedly, like this:

    <script>
function sundayPriorWeeks(weeks) {
  var today = new Date();
  // today.getDay() is current day-of-week (0=Sun ... 6=Sat)
  var lastSun9wksAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate()-(9*7+today.getDay()));
  // alter display for # weeks ago with day-of-week offset
  return lastSun9wksAgo;
}
alert(sundayPriorWeeks(9).toDateString());
</script>