JS - UTC时间转换(相差8小时解决方法)

前言

  • 后端返回的UTC时间格式
2021-09-03T22:42:05.659+00:00
  • 前端格式化后发现多了8小时:
2021/09/04 06:42:05
  • 其原因是北京时间与UTC时间相差8个时区,用了常规获取日期数据的方法:
date.getFullYear()
date.getMonth()

修改方法

  • 使用getUTC***()方法获取
/**
 * UTC时间转换
 * @returns {string}
 * @param datetime UTC时间
 * @param dateSeprator 日期拼接符
 * @param timeSeprator 时间拼接符
 * @Eexample dateFormat("2021-09-03T22:42:05.659+00:00", "/", ":")
 *           dateFormat("2021-09-03T22:42:05.659+00:00")
 */
export function transTimestamp(datetime, dateSeprator = '/', timeSeprator = ':') {
  if (datetime) {
    const date = new Date(datetime)
    const year = `${date.getUTCFullYear()}`
    let month = `${date.getUTCMonth() + 1}`
    let day = `${date.getUTCDate()}`
    let hour = `${date.getUTCHours()}`
    let minute = `${date.getUTCMinutes()}`
    let second = `${date.getUTCSeconds()}`

    if (month.length === 1) {
      month = `0${month}`
    }
    if (day.length === 1) {
      day = `0${day}`
    }
    if (day.length === 1) {
      day = `0${day}`
    }
    if (hour.length === 1) {
      hour = `0${hour}`
    }
    if (minute.length === 1) {
      minute = `0${minute}`
    }
    if (second.length === 1) {
      second = `0${second}`
    }
    return `${year}${dateSeprator}${month}${dateSeprator}${day} ${hour}${timeSeprator}${minute}${timeSeprator}${second}`
  }
}
  • 结果如下:
2021/09/03 22:42:05

- End -
点赞加收藏
小手留余香
posted @ 2021-09-18 11:17  Maggieq8324  阅读(3373)  评论(0编辑  收藏  举报