前言
項(xiàng)目中經(jīng)常需要通過(guò)new Date()獲取時(shí)間,但是獲取到的時(shí)間需要我們個(gè)人進(jìn)行年月日拼接,做法比較麻煩,以下方法綁定在new Date()迹卢,可以根據(jù)個(gè)人需求來(lái)輸出我們想要的時(shí)間。
// 對(duì)Date的擴(kuò)展徒仓,將 Date 轉(zhuǎn)化為指定格式的String
// 月(M)腐碱、日(d)、小時(shí)(h)、分(m)症见、秒(s)喂走、季度(q) 可以用 1-2 個(gè)占位符,
// 年(y)可以用 1-4 個(gè)占位符谋作,毫秒(S)只能用 1 個(gè)占位符(是 1-3 位的數(shù)字)
Date.prototype.Format = function(fmt) { //author: meizz
let o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小時(shí)
"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 (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;
}
根據(jù)需求修改時(shí)間格式
console.log((new Date()).Format("yyyy-MM-dd hh:mm:ss.S"));
console.log((new Date()).Format("yyyy-M-d h:m:s.S"));
data1.png
獲取時(shí)間戳
let timestamp1 = (new Date()).valueOf();
let timestamp2 = (new Date()).getTime();
console.log(timestamp1);
console.log(timestamp2);//這兩種方法均可
data2.png