日期格式化

 1 // 日期格式化
 2 export function parseTime(time, pattern) {
 3     if (arguments.length === 0 || !time) {
 4         return null
 5     }
 6     const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
 7     let date
 8     if (typeof time === 'object') {
 9         date = time
10     } else {
11         if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
12             time = parseInt(time)
13         } else if (typeof time === 'string') {
14             time = time.replace(new RegExp(/-/gm), '/');
15         }
16         if ((typeof time === 'number') && (time.toString().length === 10)) {
17             time = time * 1000
18         }
19         date = new Date(time)
20     }
21     const formatObj = {
22         y: date.getFullYear(),
23         m: date.getMonth() + 1,
24         d: date.getDate(),
25         h: date.getHours(),
26         i: date.getMinutes(),
27         s: date.getSeconds(),
28         a: date.getDay()
29     }
30     const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
31         let value = formatObj[key]
32         // Note: getDay() returns 0 on Sunday
33         if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
34         if (result.length > 0 && value < 10) {
35             value = '0' + value
36         }
37         return value || 0
38     })
39     return time_str
40 }

 

上一篇:ES5 node环境下调用别的js文件中的函数


下一篇:JS学习笔记