将UTC时间转换为当地的时间

在哪个国建就按当地的时区展示

 

比如:我从后端获取的数据是UTC格式:'2020-09-08 12:23:33' (后端存数据是按照UTC存的,给我返的数据是这种格式,并且是字符串) 

在美国应该按照美国的时区展示,在韩国应该按照韩国(东九区)的时区展示如:'2020-09-08 21:23:33' 

具体代码:

形参date就是传递过来的utc数据,就是'2020-09-08 12:23:33' 这个字符串

思路:先转换为date对象,使用moment.js,在转换为当地的时间

import moment from 'moment'
const transFormTimeToLocalTime = date => {
  if (date) {
    const stillUtc = moment.utc(date).toDate()

    return moment(stillUtc)
      .local()
      .format('DD/MM/YYYY HH:mm:ss')
  } else {
    return '--'
  }
}

const transFormTimeToLocalDate = date => {
  if (date) {
    const stillUtc = moment.utc(date).toDate()

    return moment(stillUtc)
      .local()
      .format('DD/MM/YYYY')
  } else {
    return '--'
  }
}

 

如果后端反的是时间戳,如:1605773943,那么之间转换为日期格式就好了

这个时间戳转换为日期格式之后,你在哪个时区就按照哪个时区显示:

// 将时间戳转换成Y-m-d H:i:s
export function timestampToTime(timestamp) {
  const date = new Date(timestamp * 1000) // 时间戳为10位需*1000,时间戳为13位的话不需乘1000
  const year = date.getFullYear()
  const month =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  const minutes =
    date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  const seconds =
    date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return (
    year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  )
}

 

 

posted @ 2020-09-15 19:33  haha-uu  阅读(1444)  评论(0编辑  收藏  举报