javascript時間日期格式化例項程式碼

antzone發表於2017-03-14

往往預設的時間格式的美觀度總是讓人非常失望的,這回嚴重影響網頁的美觀度,所以對時間進行格式化是必須進行的一項工作,下面是一段來源於網路的程式碼,下面就來做一下簡單的分析,希望能夠給大家帶來一定的幫助。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
function dateFormat(date,format) 
{
  if(format===undefined)
  {
    format=date;
    date=new Date();
  }
  var map={
    "M": date.getMonth() + 1, //月份
    "d": date.getDate(), //日
    "h": date.getHours(), //小時
    "m": date.getMinutes(), //分
    "s": date.getSeconds(), //秒
    "q": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
   
  format = format.replace(/([yMdhmsqS])+/g,function(all, t){
    var v = map[t];
    if(v !== undefined)
    {
      if(all.length > 1)
      {
        v = '0' + v;
        v = v.substr(v.length-2);
      }
      return v;
    }
    else if(t === 'y')
    {
      return (date.getFullYear() + '').substr(4 - all.length);
    }
    return all;
  });
  return format;
}
console.log(dateFormat('yyyy-MM-dd hh:mm:ss'));
console.log(dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'));
console.log(dateFormat('yyyy-MM-dd'));

相關文章