参数:1.time a.可以是字符串 '2020-08-20 12:00:00'、'2020/08/20 12:00:00'、'2020/08/20'... b.也可以是Date类型 c.也可以是时间戳
2.formatStr 需要返回的时间格式 a. 'YYYY-DD-MM hh:mm:ss'、'YYYY-DD-MM'、'hh:mm:ss'... b. "W": week c.'YYYY年MM月DD日 hh点mm分ss秒'
实例:
View Code
console.log(___formatTime(new Date(), 'YYYY年MM月DD日 hh点mm分ss秒')); // 2020年08月20日 11点54分09秒
console.log(___formatTime(new Date().getTime(), 'W')); // 四
console.log(___formatTime('2020-08-20', 'YYYY/MM/DD')) // 2020/08/20
1 /** 2 * Converts the target to a time string in the specified format 3 * @param {number | string | Date} time Timestamp or time string or Date type 4 * @param {string} formatStr 'YYYY-MM-DD hh:mm:ss' 'W' .... 5 * @return {string} 6 */ 7 function ___formatTime(time, formatStr) { 8 if (!time) return; 9 var _time; 10 if (time instanceof Date) { 11 _time = time; 12 } else if (typeof time === 'string' && time.indexOf('-') > -1) { 13 _time = new Date(time.replace(/[-]/g, '/')); 14 } else { 15 _time = new Date(time); 16 } 17 var date = { 18 year: _time.getFullYear(), 19 month: _time.getMonth() + 1, 20 date: _time.getDate(), 21 day: _time.getDay(), 22 hours: _time.getHours(), 23 minutes: _time.getMinutes(), 24 seconds: _time.getSeconds(), 25 time: _time.getHours() >= 12 ? ["am", "u4e0au5348"] : ["pm", "u4e0bu5348"] 26 }, 27 reg = { 28 year: /Y+/, 29 date: /D+/, 30 month: /M+/, 31 day: /W/, 32 hours: /h+/i, 33 minutes: /m+/, 34 seconds: /s+/, 35 time: /t/i 36 }, 37 dateList = ["u65e5", "u4e00", "u4e8c", "u4e09", "u56db", "u4e94", "u516d"], 38 k, _p 39 for (k in reg) { 40 _p = reg[k]; 41 formatStr = formatStr.replace(_p, function (segment, index, originStr) { 42 var l = segment.length, 43 value = date[k], 44 str; 45 switch (k) { 46 case "day": 47 str = dateList[value]; 48 break; 49 case "hours": 50 str = (segment.toLowerCase() === segment ? value % 12 : value).toString(); 51 break; 52 case "time": 53 str = segment.toLowerCase() === segment ? value[0] : value[1] 54 break; 55 } 56 if (k != "day" && k != "time") { 57 if (l === 1) { 58 str = value 59 } else { 60 str = ("000" + value).slice(-l); 61 } 62 } 63 return str; 64 }) 65 } 66 return formatStr 67 }