时间戳、时分秒格式化转换

262 阅读1分钟

1.后端返回的秒为单位

进行时分秒转换

  filters: {
    // 将秒转换成几小时几分几秒
    getDuration(second) {
      // var days = second / (1000 * 60 * 60 * 24);
      // var hours = (second % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
      // var minutes = (second % (1000 * 60 * 60)) / (1000 * 60);
      // var seconds = (second % (1000 * 60)) / 1000;
      var days = Math.floor(second / 86400);
      var hours = Math.floor((second % 86400) / 3600000);
      if (hours < 10) {
        hours = "0" + hours;
      }
      var minutes = Math.floor(((second % 86400) % 3600) / 60);
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      var seconds = Math.floor(((second % 86400) % 3600) % 60);
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      var duration = hours + ":" + minutes + ":" + seconds;
      return duration;
    },
  },

2.日期格式化

返回的是时间戳,进行格式化处理

/*
 * 日期格式化函数                                                                   
 * @param date 日期对象                                                          
 * @param format 日期格式,默认为 YYYY-MM-DD HH:mm:ss                                
 */                                                                          
 export const formatDate = (date: Date, format = 'YYYY-MM-DD HH:mm:ss') => { 
     // 获取年月日时分秒,通过 padStart 补 0                                              
     const year = String(date.getFullYear())                                     
     const month = String(date.getMonth() + 1).padStart(2, '0')                  
     const day = String(date.getDate()).padStart(2, '0')                         
     const hours = String(date.getHours()).padStart(2, '0')                      
     const minutes = String(date.getMinutes()).padStart(2, '0')                  
     const seconds = String(date.getSeconds()).padStart(2, '0')                  
                                                                            
 // 返回格式化后的结果                                                             
 return format                                                               
     .replace('YYYY', year)                                                      
     .replace('MM', month)                                                       
     .replace('DD', day)                                                         
     .replace('HH', hours)                                                       
     .replace('mm', minutes)                                                     
     .replace('ss', seconds)                                                    
 }