如何在Javascript中格式化时间戳,以显示相关时区中的正确时间



我在JavaScript中处理时间有问题。我在firebase中的一个文档中有一个时间戳,我有一个云函数,它应该发送一个通知。我想发送通知,并将时间戳正确格式化为英国的当前时区(当前为BST或UTC+1或GMT+1(。下面是我的代码。。。

exports.sendNotificationNewRota = functions.firestore
.document('rota/{attendanceId}')
.onCreate(async snapshot => {
const transaction = snapshot.data();
var dateIn = transaction.timeIn.toDate();
let timeIn = dateIn.toLocaleTimeString( {
timezone: 'Europe/London',
timeZoneName: 'long',
hour: '2-digit',
minute:'2-digit'});
console.log(timeIn);

这个代码的输出给我一个UTC时间。当BST结束时,这可能很好,但现在不行。有没有办法适当地处理时间?

感谢

注意Date.prototype.toLocaleTimeString()的函数签名
dateObj.toLocaleTimeString([locales[, options]])

详情在这里

您可以有效地将配置传递给locales参数,为了使代码正常工作,您需要添加一个空的第一个参数。或者,您也可以将其指定为'en-UK',例如:

exports.sendNotificationNewRota = functions.firestore
.document('rota/{attendanceId}')
.onCreate(async snapshot => {
const transaction = snapshot.data();
var dateIn = transaction.timeIn.toDate();
let timeIn = dateIn.toLocaleTimeString([],{ //<-- fix here
timezone: 'Europe/London',
timeZoneName: 'long',
hour: '2-digit',
minute:'2-digit'});
console.log(timeIn);

Omg我在这个问题上浪费了很多时间,但最终我意识到这是我代码中的一个拼写错误。任何有同样问题的人都要确保使用timeZone而不是timezone

最新更新