Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var 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;
};
/**
* 格式化日期
* @param date 时间
* @param pattern 格式
* @returns {*}
*/
export function formatDate(date, pattern) {
if (!date) return date;
let SIGN_REGEXP = /([yMdHsm])(\1*)/g;
let DEFAULT_PATTERN = 'yyyy-MM-dd HH:mm:ss';
if (/^\d+$/.test(date)) {
date = new Date(+date);
} else {
if (typeof date === 'string') {
date = new Date(date);
}
}
pattern = pattern || DEFAULT_PATTERN;
return pattern.replace(SIGN_REGEXP, function ($0) {
switch ($0.charAt(0)) {
case 'y':
return padding(date.getFullYear(), $0.length);
case 'M':
return padding(date.getMonth() + 1, $0.length);
case 'd':
return padding(date.getDate(), $0.length);
case 'w':
return date.getDay() + 1;
case 'H':
return padding(date.getHours(), $0.length);
case 'm':
return padding(date.getMinutes(), $0.length);
case 's':
return padding(date.getSeconds(), $0.length);
}
});
}
/**
* 格式化日期
* @param value 数据
* @param num 小数位
* @returns String
*/
export const formatMoney = (value, num = 2) => {
let _a = num > 0 ? '.' : ''
for (let i = 0; i < num; i++) {
_a += '0'
}
if (!value) {
return '0' + _a
}
if (value.replace) {
value = value.replace(/,/g, '')
}
let val = String(value)
if (val.indexOf('.') < 0) {
return val.replace(/(?=\B(?:\d{3})+\b)(\d{3}(\.\d+$)?)/g, ',$1') + _a
} else {
return Number(value).toFixed(num).replace(/(?=\B(?:\d{3})+\b)(\d{3}(\.\d+$)?)/g, ',$1')
}
}
定义Date.prototype.Format
最新推荐文章于 2022-10-13 11:08:26 发布