1、js版本
Date.prototype.format=function(pattern){//日期格式化
var returnValue=pattern;
var format={
"y+":this.getFullYear(),
"M+":this.getMonth()+1,
"d+":this.getDate(),
"H+":this.getHours(),
"m+":this.getMinutes(),
"s+":this.getSeconds(),
"S":this.getMilliseconds(),
"h+":(this.getHours()%12),
"a":(this.getHours()/12)<=1?"AM":"PM"
};
for(var key in format){
var regExp=new RegExp("("+key+")");
if(regExp.test(returnValue)){
var zero="";
for(var i=0;i<RegExp.$1.length;i++){
zero+="0"
}
var replacement=RegExp.$1.length==1?format[key]:(zero+format[key]).substring(((""+format[key]).length));
returnValue=returnValue.replace(RegExp.$1,replacement)
}
}
return returnValue
};
//使用实例
//new Date().format("yyyy-MM-dd HH:mm:ss")
2、vue版本
function format(date,fmt){//日期格式化
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
let o = {
"y+":date.getFullYear(),
"M+":date.getMonth()+1,
"d+":date.getDate(),
"H+":date.getHours(),
"m+":date.getMinutes(),
"s+":date.getSeconds(),
"S":date.getMilliseconds(),
"h+":(date.getHours()%12),
"a":(date.getHours()/12)<=1?"AM":"PM"
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
}
}
return fmt;
};
function padLeftZero(str) {
return ('00' + str).substr(str.length);
}
export default {
format
}
//使用实例
//import basefunc from "@/components/basefunc.js";
//basefunc.format(new Date(),"yyyy年MM月dd日")