1

I found this code can be used to find the first date and the last date of a current month.

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

Today is 11/1/2018

I used this piece of code for a calendar I am developing for one of my projects. Even though it should return first day of the month as 2018-01-01T18:30:00.000Z it returns the first day as 2017-12-31T18:30:00.000Z and the last date as 2018-01-30T18:30:00.000Z.

But there are 31 days in January. So what is wrong with this code?

I found the code from a stackoverflow question

user4020527
  • 1
  • 8
  • 20
pavithra rox
  • 1,056
  • 3
  • 11
  • 33

1 Answers1

5

There is nothing wrong with the code. The inconsistency you see here is actually the timezone difference. Your plugin is printing the date in ISO string. To get this string in your own locale, use toLocaleString() on the date objects:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

console.log(firstDay.toLocaleString());
console.log(lastDay.toLocaleString());
31piy
  • 23,323
  • 6
  • 47
  • 67