【Vue】vue中时间格式的互相转换

4,187 阅读2分钟

1.获取特定格式时间

/*** 获取特定格式时间
* @param {Object} date 时间
* @param {String} format 格式
* @return {String} 特定格式的时间
*
* 例如:
* var now = new Date(); // Mon Jan 16 2017 14:32:22 GMT+0800 (中国标准时间)
* 方法一:formatDate(now, 'yyyy-MM-dd h:m:s'); // 2017-01-16 14:32:22
* 方法二:formatDate(now); // 2017-01-16 14:32:22
*/

// 方法一
export function formatDate(date,format){  
 let time = {      
  'M+': date.getMonth() + 1,      
  'd+': date.getDate(),      
  'h+': date.getHours(),      
  'm+': date.getMinutes(),      
  's+': date.getSeconds(),      
  'q+': Math.floor((date.getMonth() + 3) / 3),      
  'S+': date.getMilliseconds()  
 }  
 if(/(y+)/i.test(format)){      
  format = format.replace(RegExp.$1,(date.getFullYear() + '').substr(4 - RegExp.$1.length));  
 }  
 for (let k in time) {    
  if(new RegExp('(' + k + ')').test(format)){      
    format = format.replace(RegExp.$1,RegExp.$1.length === 1 ? time[k] : ('00' + time[k]).substr(('' + time[k]).length));    
  }  
 }  
 return format;
}

// 方法2
export const formatDate = function() {
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var h = date.getHours()
  var m = date.getMinutes()
  var s = date.getSeconds()
  var time = year + '-'
  if (month < 10) {time += '0'}
  time += month + '-'
  if (day < 10) {time += '0'}
  time += day + ' '
  if (h < 10) {time += '0'}
  time += h + ':'
  if (m < 10) {time += '0'}
  time += m + ':'
  if (s < 10) {time += '0'}
  time += s
  return time
  // return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
}

2.时间转时间戳

/**
* 时间转时间戳
* @param {String} time 时间
* @return {Object} 时间戳
*
* 例如:
* getTimestamp('2017-01-12'); // 1484222693
*/
export function getTimestamp(time){  
  if(time == null){      
    return null  
  }  
  return new Date(time).getTime()
}

3.时间戳转特定格式时间

/**
* 时间戳转特定格式时间
* @param {String} timestamp 时间戳
* @return {String} 特点格式时间
*
* 例如:
* timestampFormatDate('1484222693', 'yyyy-MM-dd'); // 2017-01-12
*/
import { formatDate } from "./formatDate";
import { timestampToDate } from "./timestampToDate";

export function timestampFormatDate(timestamp,format){    
  let date = timestampToDate(timestamp);   
  let result = formatDate(date,format);    
  return result;
}

4.时间戳转时间

/**
* 时间戳转时间
* @param {String} timestamp 时间戳
* @return {Object} 时间
*
* 例如:
* timestampToDate('1484222693'); // Thu Jan 12 2017 20:04:53 GMT+0800 (中国标准时间)
*/
export function timestampToDate(timestamp){    
  let date = new Date();    
  date.setTime(timestamp * 1000)        
  return date
}