0

I'm trying to set a date with 4 days range (From: today - 2, To: today + 2). Today, on 31. august I found the bug in my code, which says Invalid date. I'm changing the date like this, and If I console.log() it, it says -1.

Any help would be appreciated.

date: Date = new Date();
defaultDay: string = ("0" + (this.date.getDate() - 2)).slice(-2)

P.S: I checked the moment.JS library, but currently I don't have that much time to change the whole project to it.

Ravi Mariya
  • 1,210
  • 15
  • 19
HC1122
  • 404
  • 1
  • 6
  • 19
  • 1
    This should give you an idea https://stackoverflow.com/questions/563406/add-days-to-javascript-date – Akrion Aug 01 '18 at 06:35

3 Answers3

2

You're doing the basic arithmetic. Subtracting 2 from 1 will result in -1. You may try to set the date first and then get the day from the date object.

The reason is that setDate() sets the day relatively when the argument is not in the range (less than or equal to 0).

let start = new Date();
let end = new Date();
start.setDate(start.getDate() - 2);
end.setDate(end.getDate() + 2);
console.log(start.getDate(), end.getDate());
31piy
  • 23,323
  • 6
  • 47
  • 67
  • Yes, I came across that solution. But I wonder if it is possible to do that without setting new Date two times? – HC1122 Aug 01 '18 at 06:37
  • @HC1122 -- Not sure why don't you want to set the day? Is there a restriction? This seems a correct approach, which works in all scenarios. – 31piy Aug 01 '18 at 06:38
  • It is not the problem in setting date, I just wonder if it is possible without intializing two dates (start and end, so to have only one of those). – HC1122 Aug 01 '18 at 06:39
  • @HC1122 -- Not sure if it is too easy in plain JS. – 31piy Aug 01 '18 at 06:40
  • Well, than I'm gonna use that solution. Thank you for your help, will accept answer in 5 minutes. – HC1122 Aug 01 '18 at 06:41
1

you can use date api for avoid issues. here is an example

let date = new Date();
date.setDate(date.getDate() - 2);
console.log(("0" + date.getDate()).slice(-2));

but you have to remember that if you do not want to modify date itself then you have to clone it

taburetkin
  • 313
  • 3
  • 17
0

You can always do in a way @31piy has suggested. But Date handling is lot easier if you do it using MomentJS.

You can do it easily like

const today = moment()
const two_days_after_today = moment().add(2, 'day')
const two_days_before_today = moment().subtract(2, 'day')
Sandip Nirmal
  • 2,283
  • 21
  • 24