在MSSQL数据库中使用GETDATE()函数获取时间,是正常操作,但这个时间获取的是当地时间。但是还有一个函数GETUTCDATE(),这个函数是获取的世界标准时间,两个函数之间存在这时区的差异。
那么问题来了,在Nodejs中直接从数据库中读取回来的时间,在浏览器中直接显示是正常的,但会显示成2024-05-14T10:55:20.883Z这样的格式,当你需要格式化一下显示成2024-05-14 10:55:20的时候,就会涉及到一个时区的问题,可能这个时间会显示成2024-05-14 18:55:20,多了8个小时,因为系统时区是'Asia/Shanghai',下面两个格式化程序都会有这样的问题
const formatDateTime= (time) => {
const date = new Date(time)
const YY = date.getFullYear() + '-'
const MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
const DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
const hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
const mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
const ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return YY + MM + DD + ' ' + hh + mm + ss
},
const formatByMomentTimezone=(time) => {
console.log('Time:', time)
// set true:not get Cache
let timezoneName = moment.tz.guess(true)
// 首先调用 Intl.DateTimeFormat().resolvedOptions().timeZone
console.log('timezoneName', timezoneName)
const resDate = moment.tz(time, timezoneName)?.format()
return resDate || '' //
},
最终解决方案,将MSSQL数据库中GETDATE()换成GETUTCDATE(),这样一来所有的时间都是国际标准时间,NodeJS在做时间转换的时候都正常了。
这个坑爬了整整一天时间。哎。。。。。以前没注意这个小细节。