第一种:将时间戳转化为标准时间
方法一:
var date = new Date(时间戳); //获取一个时间对象
function format(fmt, date) {
var o = {
"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+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
调用函数把var times= new Date(时间戳)获取到的时间转化为标准时间
调用方式
console.log(format('yyyy-MM-dd hh:mm:ss', times))
console.log(format('yyyy-MM-dd', times))
console.log(format('yyyy/MM/dd', times))
console.log(format('yyyy年MM月dd日', times))
方法二:
// 日期的格式化 code = new Date() var data = (new Date()).getTime() 获取时间戳
参数说明: code为时间戳, true表示显示年月日 false表示显示年月日很时间
export function formatTimes(code, boolean) {
const time = new Date(code)
const year = time.getFullYear()
const month = time.getMonth() + 1
const date = time.getDate()
const hour = time.getHours() < 10 ? '0' + time.getHours() : time.getHours()
const min = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
const sec = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
if (boolean) {
return year + '-' + month + '-' + date + ''
} else {
return year + '-' + month + '-' + date + '.' + hour + ':' + min + ':' + sec
}
}
第二种:将标准时间转化为时间戳
var nowData = new Date();
有三种方式可以将标准时间转化为时间戳
区别如下:
var time1 = nowData.getTime();
var time2 = nowData.valueOf();
var time3 = Date.parse(nowData);
前两种是精确到毫秒,后面一种精确到秒
//1532868592176
//1532868592176
//1532868592000
这次在项目开发的时候后台返给我的数据是精确到秒,但是没有返回后面的三个零,前端处理的时候要加上三个零