Reputation: 1792
I send a date back to my backend to create.
The back end recieves the end date:
console.log(req.params.end); // req.params.end > 2019-01-17
I create a date out object out of it
var endDate = new Date(req.params.end);
console.log(endDate); endDate > 2019-01-17T00:00:00.000Z (nice)
I begin to separate the year/month/date
var endYear = endDate.getFullYear();
var endMonth = endDate.getMonth() + 1; // 1 - 12 range
var endDay = endDate.getDate();
but the day is always wrong, it's one day before:
console.log('end date : ', endDay); // end date : 16
setting the time zone doesn't make a difference (I'm EST) (before I extract the date)
var est = { timeZone: "America/New_York" };
endDate.toLocaleString("en-US", est);
I also have a start date which is fairly identical and it behaves as expected:
var startDate = new Date(req.params.year,tmpStartMonth,req.params.day);
console.log(startDate) // startDate > 2019-01-10T05:00:00.000Z (this is correct)
var startDay = startDate.getDate();
console.log(startDay) // startDay > 10
does the following time after day affect my result somehow? I'm fairly confused about what's going wrong here.
Upvotes: 0
Views: 55
Reputation: 4383
Here's what happening. When you create the Date object, you get a UTC date. In your case, you get 01/17/2019 at 00.00 UTC. I imagine you are in the US, so that date would actually be 01/16 for you.
var utcDate = new Date('2019-01-17T00:00:00.000Z');
console.log(utcDate);
console.log(utcDate.getDate()); // 16
If you instead create the date with the correct timezone for you, you will get the date that you expect. Here's an example for Pacific Time (UTC-8).
var myDate = new Date('2019-01-17T00:00:00.000-08:00');
console.log(myDate);
console.log(myDate.getDate()); // 17
Upvotes: 2
Reputation: 969
I don't see anything wrong here (example taken from mozilla getDate()
reference maybe you have to check the entry
var endDate = new Date('August 19, 1975 23:15:30');
console.log(endDate.getFullYear());
console.log(endDate.getMonth()+1); // 1 - 12 range
console.log(endDate.getDate());
Upvotes: 0