将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 '--'
  }
}

原文地址:https://www.cnblogs.com/hahahakc/p/13675015.html