title: JavaScript时间格式化
abbrlink: 26bcd43f
date: 2021-10-10 14:26:18
tags:
- Vue
categories:
- Vue技巧
JavaScript中时间格式化
有的时候,我们需要一定格式的 时间 比如2017-05-12 08:48
这样的格式。
时间格式化
第一种
function formatDate(time){
var date = new Date(time);
var year = date.getFullYear(),
month = date.getMonth() + 1,//月份是从0开始的
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
var newTime = year + '-' +
month + '-' +
day + ' ' +
hour + ':' +
min + ':' +
sec;
return newTime;
}
输出结果:
前置 0
但是这里存在一个问题,就是,我想要的格式应该是 2017-05-12 08:49:25
在月、日、时、分、秒
小于10
的时候,应该要前置一个0
。
改进代码:
第二种
function formatDate(time){
var date = new Date(time);
var year = date.getFullYear(),
month = date.getMonth()+1,//月份是从0开始的
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
var newTime = year + '-' +
(month < 10 ? '0' + month : month) + '-' +
(day < 10 ? '0' + day : day) + ' ' +
(hour < 10 ? '0' + hour : hour) + ':' +
(min < 10 ? '0' + min : min) + ':' +
(sec < 10 ? '0' + sec : sec);
return newTime;
}
formatDate(new Date().getTime());//2017-05-12 09:09:21
处理UTC格式时间
在前后端数据接口通信中,后台返回的时间往往是 UTC 格式的,即2020-10-12T10:31:35.891724+00:00
这种,这可能是因为在数据库中存储时间格式选择的是 TIMESTAMP。
作为前端,我们需要将其转换为标准的本地格式,并用“YYYY-MM-DD HH:mm:ss”这种格式呈现给用户,用户才能看得懂。
转换
formatTime(time) {
let date = new Date(time).toJSON()
return new Date(+new Date(date) + 8 * 3600 * 1000)
.toISOString()
.replace(/T/g, ' ')
.replace(/\.[\d]{3}Z/, '')
}