今天写页面发现这么一个问题:将后台传来的时间格式化,本来是一个很简单的问题,但是搞了好久发现转换不对,百度了很久,自己写的和别人差不多,没发现什么问题。
原本的代码:
function _getDate(time) {
let str = null
let date = new Date(str)
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
let hours = date.getHours()
let mi = date.getMinutes()
let seconds = date.getSeconds()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
if (hours < 10) {
hours = '0' + hours
}
if (mi < 10) {
mi = '0' + mi
}
if (seconds < 10) {
seconds = '0' + seconds
}
let t = year + '-' + month + '-' + day + " / " + hours + ":" + mi + ":" + seconds
return t
}
但是转换出来的日期就是不对,到底是什么问题呢?
由于后端传过来的数据是GMT的,所以到了前端需要做一下判断,一定要加上if那一段
function _getDate(time) {
let str = null
if (time != null) {
str = time.replace("GMT", "")
}
let date = new Date(str)
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
let hours = date.getHours()
let mi = date.getMinutes()
let seconds = date.getSeconds()
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
if (hours < 10) {
hours = '0' + hours
}
if (mi < 10) {
mi = '0' + mi
}
if (seconds < 10) {
seconds = '0' + seconds
}
let t = year + '-' + month + '-' + day + " / " + hours + ":" + mi + ":" + seconds
console.log(t)
return t
}
没加if:
加了if: