// 获取下个月的特定一天
getSpecificDayOfNextMonth(day, dayEnd = 0) {
let now = new Date();
now.setMonth(now.getMonth() + 1, day); // 设置月份加一,日期设置为特定的一天
if (dayEnd) {
const newYear = now.getFullYear();
const newMonth = now.getMonth() + 1; // 注意getMonth()返回的是0-11,所以要加1
const newDay = now.getDate(); // 日期
const newDateTime = `${newYear}-${newMonth}-${newDay} 23:59:59`
now = new Date(newDateTime)
return now
}
return now;
}
// 获取指定年月的第一天
getFirstDayOfMonth(year, month) {
return new Date(year, month - 1, 1);
}
// 获取指定年月的最后一天
getLastDayOfMonth(year, month, dayEnd) {
let lastDate
if (dayEnd) {
lastDate = new Date(year, month, 0, 23, 59, 59)
} else {
lastDate = new Date(year, month, 0);
}
return lastDate
}
// 格式化带时区的时间
formatDate(date, type = 'date') {
if (!date) {
return ''
}
let dateObj = new Date(date); // 'Thu April 12 2021 22:03:00 GMT+0800 (中国标准时间)'
let datetime
// 获取年份、月份和日期
let year = dateObj.getFullYear();
let month = dateObj.getMonth() + 1; // 月份是从 0 开始的,所以需要加 1
let day = dateObj.getDate();
let hour = dateObj.getHours();
let minute = dateObj.getMinutes();
let second = dateObj.getSeconds();
// 将月份和日期转换成两位数格式
let formattedMonth = month.toString().padStart(2, '0');
let formattedDay = day.toString().padStart(2, '0');
let formattedHour = hour.toString().padStart(2, '0');
let formattedMinute = minute.toString().padStart(2, '0');
let formattedSecond = second.toString().padStart(2, '0');
if (type === 'month') {
datetime = year + '-' + formattedMonth
} else if (type === 'datetime') {
datetime = year + '-' + formattedMonth + '-' + formattedDay + " " + formattedHour + ':' + formattedMinute + ':' + formattedSecond
} else {
datetime = year + '-' + formattedMonth + '-' + formattedDay
}
return datetime;
}