vue 封装日期格式转换

146 阅读1分钟

在写vue项目的时候总是遇到日期格式需要统一的问题,于是自己封装了一个自由改变日期格式的方法,可以在任何veu 的组件内调用

/** 
* 转换时间格式 * @param {String | Date} timestamp - 要转换的数据 
* @param { String } format - 要转换的时间格式 
* @returns {string} 
*/
export function formatTimestamp(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {  
       const date = new Date(timestamp)  const replacer = (match, key) => {    
            const method = formatMap[key]    
            let value    
            if (method === 'getMonth') {    
                value = date[method]() + 1 // 月份需要加1  
               } else {   
                  value = date[method]()  
               }    
               return padZero(value, key === 'SSS' ? 3 : 2)  }  
               const formatMap = {   
                YYYY: 'getFullYear',  
                MM: 'getMonth',  
                DD: 'getDate',  
                HH: 'getHours',  
                mm: 'getMinutes', 
                ss: 'getSeconds',  
                SSS: 'getMilliseconds' 
               } 
              return format.replace(/(YYYY|MM|DD|HH|mm|ss|SSS)/g, replacer)}
            // 值补零函数
            export function padZero(value, length = 2) {  return String(value).padStart(length, '0')}

在组件内调用

console.log(formatTimestamp(Date.now(), 'YYYY-MM-DD')); // 输出类似 "2023-09-40"

仅供学习和参考