daydreamer daydreamer -3 years ago 121
Javascript Question

Javascript not taking day in Date() constructor correctly

I am developing an API where a user can ask for transactions in a given year and month. The API looks like

routes.get('/transactions/:member_id/:year/:month', (req, res) => {
let {member_id, year, month} = req.params;
let start_date = new Date(year, month - 1, 1);
let end_date = moment(start_date).add(1, 'months');

console.log({start_date, end_date});
res.send({start_date, end_date})
});


I am using
ExpressJS
to build API and
momentjs
to manipulate dates.

When I hit this api as http://localhost:8080/transactions/m/2017/10, I ask transactions for user
m
, year
2017
and month
10
which is October (this is why I do
month - 1
in my implementation above).

What I get back in
console
is

{ start_date: 2017-09-30T11:00:00.000Z,
end_date: moment("2017-11-01T00:00:00.000") }


I am confused because start day of the month has been hardcoded as
1


let start_date = new Date(year, month - 1, 1);


and not
30
. What is going wrong here?

Answer Source

That's an issue with the timezone. What you can do is:

let start_date = new Date(year, --month);
start_date.setUTCDate(1);

JavaScript Date() uses client local timezone. To get a consistent result, JavaScript Date() has utc methods to help standardize the date based on the GMT World Standard Time. Check MDN's JavaScript Date Reference

Alternatively, you can also do this:

let start_date = new Date(Date.UTC(year, --month, 1));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download