JS 時(shí)間轉(zhuǎn)換

JS中沒有格式化字符串的功能,因此在此整理一下,免得總需要網(wǎng)上查詢:
我們可以采用給Date添加prototype的方式,也可以單獨(dú)使用字符串的方式來(lái),其實(shí)內(nèi)部功能是一樣的。

prototype 方式

// 對(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ù)字) 
// 例子: 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var 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 (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;
}
調(diào)用: 

var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss"); 

直接調(diào)用方式

// 因?yàn)閱为?dú)函數(shù),需要格式化的日期必須單獨(dú)傳入,第一個(gè)參數(shù)是日期,第二個(gè)參數(shù)與上面一樣
function dateFormatter(d, fmt) {
  const date = new Date(d);
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小時(shí)
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (const 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;
}

調(diào)用:
dateFormatter(new Date(), 'yyyy-MM-dd');
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容