Reputation: 305
I need to fetch the first and last day of the current month. I created the solution using the core JS new Date() method.
const date = new Date();
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
console.log(firstDay.toUTCString(), lastDay.toUTCString()); //Tue, 31 Mar 2020 18:30:00 GMT Wed, 29 Apr 2020 18:30:00 GMT
When I try a similar thing in the browser's console, it prints the result as expected, i.e. 1st April 2020 and 30th April 2020
, but testing it in the postman environment, gives the wrong result.
Can anyone please help to resolve this confusion?
Upvotes: 0
Views: 222
Reputation: 2829
Your code:
var d = new Date(),
e = new Date(d.getFullYear(), d.getMonth(), 1),
f = new Date(d.getFullYear(), d.getMonth() + 1, 0);
console.log(e.toUTCString() + "\n" + f.toUTCString());
so you get wrong result because you want to get the UTC string from local date, you need to make it UTC date in order to print UTC string correctly.
var d = new Date(),
e = new Date(Date.UTC(d.getFullYear(), d.getMonth(), 1)),
f = new Date(Date.UTC(d.getFullYear(), d.getMonth() + 1, 0));
console.log(e.toUTCString() + "\n" + f.toUTCString());
Upvotes: 2