在哪個國建就按當地的時區展示
比如:我從后端獲取的數據是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 ) }