我从获取月初的日期开始:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
然后我将其转换为 ISO:
firstDay = firstDay.toISOString();
为什么第一天我得到2019-05-31
而不是2019-06-01
?
您可以使用简单的正则表达式来格式化字符串:
/(d{4})-(d{2})-(d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(d{4})-(d{2})-(d{2}).+/, '$3-$2-$1')
console.log(formatted)
默认的javascript日期使用您的本地时区,通过将其转换为其他时区,您可以最终得到不同的日期。
你可以做到
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
javascript 中的 date 对象可能有些棘手。当您创建日期时,它是在本地时区创建的,但 toISOString(( 会根据 UTC 获取日期。以下内容应将日期转换为 ISO,但将其保留在您自己的时区中。
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);