AI智能
改变未来

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

TOC

前言

  • 后端返回的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 -﹀﹀﹀点赞加收藏小手留余香

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » JS – UTC时间转换(相差8小时解决方法)