一、时间转换成时间戳
/**
* 13位时间戳
* @param{str} date不传默认获取当前时间戳
* getTimeStamp('2019/4/22 11:43:30')
*/
function getTimeStamp(date) {
var timeStamp = date ? (new Date(date)).getTime() : (new Date()).getTime();
return timeStamp;
}
/**
* 10位时间戳
* @param{str} date不传默认获取当前时间戳
* getTimeStamp('2019/4/22 11:43:30')
*/
function getTimeStamp(date) {
var timeStamp = date ? (new Date(date)).getTime() : (new Date()).getTime();
return parseInt(timeStamp / 1000);
}
二、时间戳转换成日期
Date.prototype.format = function(format) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
/**
* 时间戳转换成日期
* @param{number} date10位或者13位时间戳,不传默认获取当前时间
* @param{string} pattern找转换成的格式
* getTimeStamp('2019/4/22 11:43:30')
*/
function formatDate(date, pattern) {
var timer= var timer = date ? new Date(date.toString().length == 10 ? date * 1000 : date) : new Date();
if (!pattern)
pattern = "yyyy-MM-dd";
return timer.format(pattern);
}