var month = 0; // January
var d = new Date(2008, month + 1, 0);
alert(d); // last day in January
IE 6: Thu Jan 31 00:00:00 CST 2008
IE 7: Thu Jan 31 00:00:00 CST 2008
IE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008
Opera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600
Firefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Firefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Выходные различия происходят из-за различий в toString()
реализация, не потому что даты отличаются.
, Конечно, просто потому что браузеры, определенные выше использования 0 как в последний день предыдущего месяца, не означают, что продолжат делать так, или это, браузеры, не перечисленные, сделают так, но это предоставляет доверие вере, что это должно работать тот же путь в каждом браузере.
Я использовал бы промежуточную дату с первым днем следующего месяца и возвратил бы дату с предыдущего дня:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
Вот ответ, который сохраняет GMT и время начальной даты
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var last_date = new Date(first_date); //Make a copy of the calculated first day
last_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month
last_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month
console.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd
const today = new Date();
let beginDate = new Date();
let endDate = new Date();
// fist date of montg
beginDate = new Date(
`${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`
);
// end date of month
// set next Month first Date
endDate = new Date(
`${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`
);
// deducting 1 day
endDate.setDate(0);