1

I have this prop this.props.SearchDate coming in as a format like this 2016-03-31 (yyyy-MM-DD)

If I do

let date = new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().substring(0,10);
console.log(date) 

I get the correct yesterday date, but if I do

let date = new Date(new Date().setDate(new Date(this.props.SearchDate).getDate() - 1)).toISOString().substring(0,10);
console.log(date) 

I get 2019-04-29

If I remove -1, then it gets the date 30. Though actually since current date there is 31 then -1 should make day before 30.

All I need from date is to give it yyyy-mm-dd some date, and get exactly 1 date before than that. Can anyone see the problem here? This seem to be explained here: Why does js subtract a day from a Date object with a certain format?

I will share the solution to my problem.

Extelliqent
  • 1,760
  • 5
  • 32
  • 51
  • 1
    converting to unix time and subtracting a day's worth of milliseconds might be easier `new Date(new Date('2016-03-31').valueOf() - 86400000)` – Daniel Lizik Apr 04 '19 at 17:41
  • 1
    If you're doing a lot of date manipulation, you should consider using a library dedicated to dates, like [Moment.js](http://momentjs.com) or [date-fns](https://date-fns.org/). Dealing with dates and time zones is hard work. – Heretic Monkey Apr 04 '19 at 17:44
  • 1
    Note that `toISOString` returns the date and time in UTC, which is likely different from your local time zone. You need to adjust for that difference if you want to use `toISOString`. – Heretic Monkey Apr 04 '19 at 17:47
  • Possible duplicate of [Why does js subtract a day from a Date object with a certain format?](https://stackoverflow.com/questions/28344408/why-does-js-subtract-a-day-from-a-date-object-with-a-certain-format) – Heretic Monkey Apr 04 '19 at 17:50

1 Answers1

0

@Daniel Lizik's answer on this did the job for me along with time zone set.

new Date(new Date('2016-03-31').valueOf() - 86400000)
Extelliqent
  • 1,760
  • 5
  • 32
  • 51