const currentDate = new Date();
const lastMonthStartDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - 1,
1
);
const lastMonthEndDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth(),
0
);
from = lastMonthStartDate.toISOString().split("T")[0];
to = lastMonthEndDate.toISOString().split("T")[0];
console.log(lastMonthStartDate, lastMonthEndDate);
console.log(from,"last month" ,to);
while executing this I am getting
1st log —->Sat Apr 01 2023 00:00:00 GMT+0530 (India Standard Time) Sun Apr 30 2023 00:00:00 GMT+0530 (India Standard Time)
2nd log—-> 2023-03-31 last month 2023-04-29
while executing this I want
1st log —->Sat Apr 01 2023 00:00:00 GMT+0530 (India Standard Time) Sun Apr 30 2023 00:00:00 GMT+0530 (India Standard Time)
2nd log—-> 2023-04-01 last month 2023-04-30
2
Answers
Try running this code,
The reason you have the issue is that
new Date(year, month, day)
generates a time in your local time zone. Your time zone is, currently, India Time Zone which is GMT+0530. Which means your are ahead of UTC by 5 and a half hours.One way to think about it is if it’s midnight in India, it will be 7:30 PM the day before in the United Kingdom. The problem arises because when you use
new Date()
it creates a date in India Time, but, when you usetoISOString()
it displays the time in UTC. So for you, the ISO (UTC) appears yesterday. For those people running your program in a region that’s behind UTC (e.g. United States) they will appear to get the correct result.You have several choices for rectifying the problem. One is to make sure all your date operations are in UTC:
Else, you need to rewrite your Javascript to be completely in local time and avoid using any UTC time at all: