HC1122
HC1122

Reputation: 414

getDate returning wrong value

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.

Upvotes: 0

Views: 340

Answers (3)

Sandip Nirmal
Sandip Nirmal

Reputation: 2459

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')

Upvotes: 0

taburetkin
taburetkin

Reputation: 313

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

Upvotes: 1

31piy
31piy

Reputation: 23859

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());

Upvotes: 2

Related Questions