開局一個時間戳,格式全靠拆。
為了節省開發者的時間,于是有人封裝了Format方法。
代碼如下:
//format方法
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;
}
使用方法:
var d2=new Date();//先建立一個時間對象
console.log(d2.Format("yyyy-MM-dd HH:mm:ss"));//結果:2018-07-23 15:11:18
console.log(d2.Format("yyyy-MM-dd hh:mm:ss"));//結果:2018-07-23 03:11:18
或者隻要其中一部分資料:
console.log(d2.Format("yyyy-MM-dd"));//結果:2018-07-23
也可以改變連接配接字元:
console.log(d2.Format("yyyy/MM/dd"));//結果:2018/07/23
console.log(d2.Format("yyyy年MM月dd日"));//結果:2018年07月22日
時間減一天:
var d=new Date();
var d2=new Date();
d2.setDate(d.getDate()-1);
console.log(d2.Format("yyyy-MM-dd hh:mm:ss"));
這還是比較友善的。