首页 > 解决方案 > 如何在 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 完成但不是现在,这可能会很好。有没有办法正确处理时间?

谢谢

标签: javascriptfirebasegoogle-cloud-functionsdatetime-format

解决方案


注意函数签名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);

推荐阅读