标准时间转换
// 标准时间转换
// time => 标准时间
// fmt => 要转换的格式(yyyy-MM-dd)
patternDate (time, fmt) {
const o = {
'M+': time.getMonth() + 1, // 月份
'd+': time.getDate(), // 日
'h+': time.getHours() % 24 === 0 ? 24 : time.getHours() % 24, // 小时
'H+': time.getHours(), // 小时
'm+': time.getMinutes(), // 分
's+': time.getSeconds(), // 秒
'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
S: time.getMilliseconds() // 毫秒
}
const week = {
0: '/u65e5',
1: '/u4e00',
2: '/u4e8c',
3: '/u4e09',
4: '/u56db',
5: '/u4e94',
6: '/u516d'
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ?
(RegExp.$1.length > 2 ? '/u661f/u671f' : '/u5468') : '') + week[time.getDay() + ''])
}
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ?
(o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt.replace(/-/g, '-')
}
时间戳转换
// 时间戳转换
// value => 时间戳
formatDate (value) {
let date = new Date(value);
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? ('0' + MM) : MM;
let d = date.getDate();
d = d < 10 ? ('0' + d) : d;
let h = date.getHours();
h = h < 10 ? ('0' + h) : h;
let m = date.getMinutes();
m = m < 10 ? ('0' + m) : m;
let s = date.getSeconds();
s = s < 10 ? ('0' + s) : s;
return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}
获取 本周、本月、本季、本年 时间范围
// 初始化查询时间
initTime(ev = 1) {
const now = new Date(); //当前日期
const nowDay = now.getDate(); //当前日
let nowDayOfWeek = now.getDay(); // 当前周
if(nowDayOfWeek == 0) nowDayOfWeek = 7;
const nowMonth = now.getMonth(); //当前月
const nowYear = now.getFullYear(); //当前年
let startTime = null;
let endTime = null;
switch(ev) {
case 1:
startTime = new Date(now.getTime() - (nowDayOfWeek - 1) * 24*60*60*1000); //本周的开始时间
endTime = new Date(now.getTime() + (7 - nowDayOfWeek) * 24*60*60*1000); //本周的结束时间
break;
case 2:
startTime = new Date(nowYear, nowMonth, 1); //本月的开始时间
endTime = new Date(nowYear, nowMonth+1, 0); //本月的结束时间
break;
case 3:
const month = nowMonth < 3 ? 1 : (nowMonth < 6 ? 3 : (nowMonth < 9 ? 6 : 9));
startTime = new Date(nowYear, month, 0); //本季的开始时间
endTime = new Date(nowYear, month + 2, 0); //本季的结束时间
break;
default:
startTime = new Date(nowYear, 0, 1); //本年的开始时间
endTime = new Date(nowYear, 12, 0); //本年的结束时间
};
// startTime => 时间戳
// endTime => 时间戳
}