/*
* @description 格式化日期时间
* @demo dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss')
* @method dateFormat
* @param {Date} d 时间
* @param {String} str 格式,默认'yyyy-MM-dd HH:mm:ss'
* @return {String} 格式化的时间
*/
function dateFormat(d, str) {
var formatStr = checkNull(str) ? 'yyyy-MM-dd HH:mm:ss' : str;
if (checkNull(d)) { // 如果日期为空,自动获取当前日期
d = new Date();
} else if (d.constructor != Date) { // 如果参数不是一个日期对象,就认为是一个标准Long值日期
d = new Date(d);
}
return formatStr .replace("yyyy", d.getFullYear())
.replace("MM", fillZero(d.getMonth() + 1))
.replace("dd", fillZero(d.getDate()))
.replace("HH", fillZero(d.getHours()))
.replace("mm", fillZero(d.getMinutes()))
.replace("ss",fillZero(d.getSeconds()))
.replace("sss", d.getMilliseconds());
// 填充0
function fillZero(value) {
return value.toString().length < 2 ? ('0' + value) : value
}
}
/*
* @description 获取指定时间
* @demo targetDate({type: 'week', num: 2});
* @method targetDate
* @param {Object} options {num: Number, date: Date, format: String , type: String }
* @return {String} 格式化的时间
*/
function targetDate(options) {
var date,
num = parseInt(options.num) || 0,
format = options.format || 'yyyy-MM-dd HH:mm:ss';
if (checkNull(options.date)) { // 如果日期为空,自动获取当前日期
date = new Date();
} else if (options.date.constructor !== Date) { // 如果参数不是一个日期对象,就认为是一个标准Long值日期
date = new Date(options.date);
}
switch (options.type) {
case "day":
date.setDate(date.getDate() + num);
return dateFormat(date, format);
case "week":
date.setDate(date.getDate() + num * 7);
return dateFormat(date, format);
case "month":
date.setMonth(date.getMonth() + num);
return dateFormat(date, format);
case "year":
date.setFullYear(date.getFullYear() + num);
return dateFormat(date, format);
case "hours":
date.setHours(date.getHours() + num);
return dateFormat(date, format);
case "minutes":
date.setMinutes(date.getMinutes() + num);
return dateFormat(date, format);
case "seconds":
date.setSeconds(date.getSeconds() + num);
return dateFormat(date, format);
default:
throw new Error('type值应为day、week、month、year、hours、minutes、seconds其中一个')
}
}
/*
* @description 判空
* @demo checkNull('')
* @method checkNull
* @param {any} value 需要校验的字符串
* @return {Boolean} true/false
*/
function checkNull(value) {
return (!value || value == null || typeof(value) == "undefined" || value == "");
}