-1

with this below code , I am getting what i need in this format YYYY-MM-DD, but I am trying DD should be -10 days from current date. in this example I am expecting to have 2022-04-04

var todayDate = new Date().toISOString().slice(0,10); 
console.log(todayDate)

Can someone please help in providing me working code. Thanks

RenaudC5
  • 3,553
  • 1
  • 11
  • 29
  • 1
    why would it be 10 days earlier? (`slice()` is just a string method it doesn't take 10 days off the date?) perhaps see: [How to subtract days from a plain Date?](https://stackoverflow.com/questions/1296358/how-to-subtract-days-from-a-plain-date) – pilchard Apr 15 '22 at 22:16
  • 1
    `date.setDate(date.getDate() - 10)` – Bravo Apr 15 '22 at 22:20
  • 1
    Duplicate of [How to subtract days from a plain Date?](https://stackoverflow.com/questions/1296358/how-to-subtract-days-from-a-plain-date) – Samathingamajig Apr 15 '22 at 22:42

2 Answers2

1

Try:

var tenDaysAgo = new Date(Date.now()- 1000 * 60 * 60 * 24 * 10)

console.log(tenDaysAgo.toISOString().slice(0, 10))

because there is 1,000 ms to a second, 60 seconds in a minute, etc.

Siva K V
  • 10,561
  • 2
  • 16
  • 29
Igor Shmukler
  • 1,742
  • 3
  • 15
  • 48
0

Slice is a js method which is used by an array (String is an array of char) and returns a shallow copy of the array selected from a start position to an end position.

According to the documentation

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

For Example, "Hello, world".slice(0,5) is equal to "Hello".


If you want to get a date 10 days earlier, you can init the current date and then take of 10 days. This can be done whith the setDate and getDate methods

const date = new Date()
date.setDate(date.getDate() - 10)
console.log(date.toISOString().slice(0,10))
RenaudC5
  • 3,553
  • 1
  • 11
  • 29