js日期格式化代码

js 日期格式化代码

分享一个前端实用的 js 日期格式化代码,相当给力。

 

 1 export function getFillDate(key) {
 2   if(key < 10) {
 3     return `0${key}`;
 4   }else{
 5     return `${key}`;
 6   }
 7 }
 8 /**
 9  * 时间戳转化为年月日
10  * @param times 时间戳
11  * @param ymd 格式类型(yyyy-mm-dd,yyyy/mm/dd)
12  * @param hms 可选,格式类型(hh,hh:mm,hh:mm:ss)
13  * @returns {年月日}
14  */
15 export function dateFomat (times, ymd,  hms) {
16   const oDate = new Date(times)
17   const oYear = oDate.getFullYear()
18   const oMonth = oDate.getMonth() + 1
19   const oDay = oDate.getDate()
20   const oHour = oDate.getHours()
21   const oMin = oDate.getMinutes()
22   const oSec = oDate.getSeconds()
23   let oTime // 最后拼接时间
24   // 年月日格式
25   switch (ymd) {
26     case 'yyyy-mm-dd':
27       oTime = oYear + '-' + getFillDate(oMonth) + '-' + getFillDate(oDay)
28       break
29     case 'yyyy/mm/dd':
30       oTime = oYear + '/' + getFillDate(oMonth) + '/' + getFillDate(oDay)
31       break
32   }
33   // 时分秒格式
34   switch (hms) {
35     case 'hh':
36       oTime = oTime + ' ' + getFillDate(oHour)
37       break
38     case 'hh:mm':
39       oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin)
40       break
41     case 'hh:mm:ss':
42       oTime = oTime + ' ' + getFillDate(oHour) + ':' + getFillDate(oMin) + ':' + getFillDate(oSec)
43       break
44   }
45   return oTime
46 }

 

效果图:

 

posted @ 2024-06-04 08:36  青茶360  阅读(6)  评论(0编辑  收藏  举报