【小分享】Date對象封裝,時間格式化函數time()

 

今天再來分享下Date的應用知識點php

先看效果,相似於php裏邊的time('yyyy-mm-dd')用法,可是我這裏沒有徹底依照php的參數格式來,若是有須要稍微修改一下就行。spa

 

首先,明確須要用到的參數:debug

一、時間戳,就是你須要格式化的時間戳;code

二、格式字符串,相似於「yy-mm-dd」;orm

 

 

具體作法無非就是獲取到「年、月、日、時、分、秒、星期」,而後作一對blabla的處理,不囉嗦,先上代碼:blog

 1 function formateDate(strTime, format, needMap) {
 2     strTime = Number(strTime);
 3     format = format || 'Y-M-D H:I:S';
 4     var date = new Date(strTime);
 5     var dateMap = {
 6         y: (date.getFullYear()+'').slice(2),
 7         Y: date.getFullYear(),
 8         M: date.getMonth() + 1,
 9         D: date.getDate(),
10         h: date.getHours()%12,
11         H: date.getHours(),
12         i: date.getMinutes(),
13         s: date.getSeconds(),
14         I: date.getMinutes() > 9 ? date.getMinutes() : ('0' + date.getMinutes()),
15         S: date.getSeconds() > 9 ? date.getSeconds() : ('0' + date.getSeconds()),
16         A: date.getHours() >= 12 ? 'pm' : 'am',
17         w: date.getDay(),
18         W: ['日','一','二','三','四','五','六'][date.getDay()]
19     };
20     for (var k in dateMap) {
21         format = format.replace(new RegExp(k, 'g'), dateMap[k]);
22     }
23     if (needMap) {
24         return dateMap;
25     }
26     return format;
27 }

 

這裏格式字符串未嚴格使用php的方式,採用了大小寫來區分字符串

 

y: 2位數年(91)
Y: 4位數年(1991)
M: 月份(10)
D: 日(15)
H: 24小時格式(19)
h: 12小時格式(7)
I: 2位分鐘(05)
i: 1位分鐘(5)
S: 2位秒(09)
s: 1位秒(9)
W: 中文周幾(三)
w: 數字周幾(3)
A: 上午/下午(am/pm)get

 

使用示例:

  • formateDate(Date.now(), 'Y-M-D H:I:S') ==> "2016-10-26 15:07:09"
  • formateDate(Date.now(), 'Y-M-D H:i:s'==> "2016-10-26 15:7:9"
  • formateDate(Date.now(), 'y-M-D | .A h:I:S') ==> "16-10-26 | .pm 3:49:32"
  • formateDate(Date.now(), 'Y-M-D H:I:S | 周W | 周w') ==> "2016-10-26 15:52:28 | 週三 | 周3"

 

時間處理你們都懂,不囉嗦,簡單說下「時間格式字符串」處理io

 

這裏其實就是屢次把傳進來的字符串作replace處理,把格式字符串中合法的字符串用對應的時間數據替換,最後返回就是咱們須要的格式了function

另外,還有最後一個參數,是做爲debug參數用的,true的時候返回整個dateMap。

 

就醬紫吧~~~

相關文章
相關標籤/搜索