0

I am trying to grab the previous dates from the current date. For instance lets take todays date 06-07-2023 I want to be able to get the 06-06-2023, 06-05-2023, 06-04-2023, etc..

Is there a way to use the date functions in Javascript to accomplish this?

Zubair Amjad
  • 621
  • 1
  • 10
  • 29

2 Answers2

0

You can use:

theDate.setDate(theDate.getDate() - 1)

admdev
  • 11
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 07 '23 at 21:46
0

Here is a function that can do that for you:

Tweak "limit" to achieve the desired output.

const getPrevDates = (limit) => {
  let initDate = new Date(); // get today's date as starting date
  let prevDates = [];

  for (let i = 0; i < limit; i++) {
    const prevDate = initDate.setDate(initDate.getDate() - 1); // Previous date in ms (unix timestamp)
    const convertedDate = (new Date(prevDate).toISOString()).slice(0, 10); // Converted ms (unix timestamp) to ISO-8601 date
    prevDates.push(convertedDate); // push convertedDate to array
  }

  return prevDates; // return array containing dates
}

console.log(getPrevDates(10)); // execute function and log result (gets 10 dates)
bigcbull
  • 41
  • 3
  • `new Date(prevDate).toISOString()` will produce an identical result to `prevDate.toISOString()`. It's unclear why you copy the date just to call *toISOString*. Also, there is no parsing happening anywhere in the *getPrevDates* function. – RobG Jun 08 '23 at 12:28
  • @RobG `prevDate` is a unix timestamp so calling `toISOString()` on it will result in TypeError. However you are correct regarding the parsing thing, I should change variable name to something else. – bigcbull Jun 08 '23 at 12:56
  • You're correct in that *prevDate* isn't a *Date* object, it's an ECMAScript time value, so my bad there. *initDate* is modified by the call to *setDate*, so the usual way to proceed after that is to just call *initDate.toISOString*. – RobG Jun 10 '23 at 06:12