JS去除Json时间日期格式带T的日期

在项目中有遇到对于后台传过来的json数据时间格式是带T的一些做法总结

方式一 

//时间格式中含有T
let date = '2022-12-15T16:14:24',
  dateTimeres = date.replace(/T/g, ' ').replace(/.[\d]{3}Z/, ' ')
console.log(dateTimeres, 'dateTimeres')

 方式二

let date = '2022-12-15T16:14:24',
  dateTimeres = new Date(+new Date(date) + 8 * 3600 * 1000)
    .toISOString()
    .replace(/T/g, ' ')
    .replace(/\.[\d]{3}Z/, '')
console.log(dateTimeres, 'dateTimeres')

 方式三 (最准确,但繁琐)

//去除Json日期格式的T
function TimeFormat(time) {
  let d = time ? new Date(time) : new Date(),
    obj = {
      year: d.getFullYear(),
      month: d.getMonth() + 1,
      day: d.getDate(),
      hours: d.getHours(),
      min: d.getMinutes(),
      seconds: d.getSeconds()
    }
  Object.keys(obj).forEach(key => {
    if (obj[key] < 10) obj[key] = `0${obj[key]}`
    // console.log(obj[key])
  })

  return `${obj.year}-${obj.month}-${obj.day} ${obj.hours}:${obj.min}:${obj.seconds}`
}
//时间格式中含有T
let date = '2022-12-15T16:14:24'
console.log(TimeFormat(date), 'dateTimeres')

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/128333303