1.获取当月第一天
currentTime() {
const currentDate = new Date();
const year = currentDate.getFullYear();//获取当前年
const month = String(currentDate.getMonth() + 1).padStart(2, "0");//获取当前月
const firstDay = "01";//日
return `${year}-${month}-${firstDay}`;
},
2.(1)获取当月最后一天
getLastDayOfNaturalMonth() {
// 获取当前日期
const currentDate = new Date();
// 获取当前年份
let year = currentDate.getFullYear();
// 获取下个月的月份,使用 padStart 在月份小于 10 时在前面补零
let month = String(currentDate.getMonth() + 2).padStart(2, "0");
// 如果月份为 '13',说明当前是12月,需要更新年份并将月份设置为 '01'
if (month === '13') {
year = year + 1;
month = '01';
}
// 设置每个月的第一天为 '01'
let firstDay = "01";
// 构建下个月的第一天的日期字符串,格式为 'YYYY-MM-DD'
const firstDayOfNextMonth = `${year}-${month}-${firstDay}`;
// 计算当前月的最后一天,通过减去一天的毫秒数来得到
const lastDayOfMonth = new Date(new Date(firstDayOfNextMonth).getTime() - 86400000);
// 将最后一天的日期转换为 ISO 格式,并提取日期部分
return lastDayOfMonth.toISOString().split("T")[0];
}
(2)获取当月最后一天 可接受传值
function getLastDayOfMonth2(year = new Date().getFullYear(), month = new Date().getMonth() + 1) {
// 构建下个月的第一天的日期对象
const firstDayOfNextMonth = new Date(year, month, 1);
// 计算当前月的最后一天(通过减去一天的毫秒数)
const lastDayOfMonth = new Date(firstDayOfNextMonth.getTime() - 86400000);
// 格式化日期为 YYYY-MM-DD 字符串
const formattedDate = `${lastDayOfMonth.getFullYear()}-${String(lastDayOfMonth.getMonth() + 1).padStart(2, '0')}-${String(lastDayOfMonth.getDate()).padStart(2, '0')}`;
return formattedDate;
}
3.当前时间
function parseTime(time, pattern) {
// 如果没有提供时间戳或时间字符串,或者时间为假值,则返回 null
if (arguments.length === 0 || !time) {
return null
}
// 定义日期时间格式,默认为 '{y}-{m}-{d} {h}:{i}:{s}'
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
// 如果 time 是对象,直接赋值给 date
if (typeof time === 'object') {
date = time
} else {
// 处理时间字符串的格式
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
}
// 处理时间戳格式
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
// 创建 Date 对象
date = new Date(time)
}
// 定义用于格式化的对象
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
// 替换格式字符串中的占位符
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// 处理星期几的情况
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
// 补零操作
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
//调用 parseTime(new Date())
//显示星期几 调用parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s} 星期{a}')
//默认格式为{y}-{m}-{d} {h}:{i}:{s},
//如需调整格式,参考:parseTime(new Date(),'{y}/{m}/{d}')