/**
* 日期处理工具类
*/
/**
* 判断闰年
* @param date Date日期对象
* @return boolean true 或false
*/
export function isLeapYear(date) {
return (0 == date.getYear() % 4 && ((date.getYear() % 100 != 0) || (date.getYear() % 400 == 0)));
}
/**
* 日期对象转换为指定格式的字符串
* @param formatStr 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
* @param date Date日期对象, 如果缺省,则为当前时间
*
* YYYY/yyyy/YY/yy 表示年份
* MM/M 月份
* W/w 星期
* dd/DD/d/D 日期
* hh/HH/h/H 时间
* mm/m 分钟
* ss/SS/s/S 秒
* @return string 指定格式的时间字符串
*/
export function dateToStr(date, formatStr) {
let str = formatStr || 'yyyy-MM-dd HH:mm:ss';
let Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, date.getFullYear().toString());
str = str.replace(/yy|YY/, (date.getFullYear() % 100) > 9 ? (date.getFullYear() % 100).toString() : '0' + (date.getFullYear() %
100));
str = str.replace(/MM/, date.getMonth() >= 9 ? (date.getMonth() + 1).toString() : '0' + (date.getMonth() + 1));
str = str.replace(/M/g, date.getMonth().toString());
str = str.replace(/w|W/g, Week[date.getDay()]);
str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
str = str.replace(/d|D/g, date.getDate().toString());
str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
str = str.replace(/h|H/g, date.getHours().toString());
str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
str = str.replace(/m/g, date.getMinutes().toString());
str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
str = str.replace(/s|S/g, date.getSeconds().toString());
return str;
}
/**
* 日期计算
* @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param num int
* @param date Date 日期对象
* @return Date 返回日期对象
*/
export function dateAdd(strInterval, num, date) {
date = date || new Date();
switch (strInterval) {
case 's':
return new Date(date.getTime() + (1000 * num));
case 'n':
return new Date(date.getTime() + (60000 * num));
case 'h':
return new Date(date.getTime() + (3600000 * num));
case 'd':
return new Date(date.getTime() + (86400000 * num));
case 'w':
return new Date(date.getTime() + ((86400000 * 7) * num));
case 'm':
return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(),
date.getSeconds());
case 'y':
return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(),
date.getSeconds());
}
}
/**
* 日期计算
* @param strInterval string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
* @param num int
* @param dateStr 字符串日期
* @param format 日期格式
*/
export function dateStrAdd(strInterval, num, dateStr, format) {
const date = strFormatToDate(format, dateStr);
const dateAdded = dateAdd(strInterval, num, date);
return dateToStr(dateAdded, format);
}
/**
* 比较日期差 dtEnd 格式为日期型或者有效