isu-element
Version:
Polymer components for building web apps.
41 lines (40 loc) • 1.24 kB
JavaScript
/*
提供公共的格式化方法
*/
/**
* @polymerBehavior
*/
export const FormatBehavior = {
properties: {},
/**
* 格式化日期
* @param date 时间戳(毫秒)
* @param fmt 显示格式,默认为'YYYY-MM-DD hh:mm:ss'
* @param emptyReturn 默认空值返回数据
*/
formatDate: function (date, fmt, emptyReturn) {
if (!date && emptyReturn) {
return emptyReturn;
}
date = date || new Date().getTime();
fmt = fmt || 'YYYY-MM-DD hh:mm:ss';
date = new Date(Number(date));
let o = {
"M+": date.getMonth() + 1, // 月份
"D+": date.getDate(), // 日
"h+": date.getHours(), // 小时
"m+": date.getMinutes(), // 分
"s+": date.getSeconds(), // 秒
"q+": Math.floor((date.getMonth() + 3) / 3), // 季度
"z": date.getMilliseconds() // 毫秒
};
if (/(Y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let 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;
}
};