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.时间转时间戳
export function getTimestamp(time){
if(time == null){
return null
}
return new Date(time).getTime()
}
3.时间戳转特定格式时间
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(
*/
export function timestampToDate(timestamp){
let date = new Date();
date.setTime(timestamp * 1000)
return date
}