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

How to format timestamp in Javascript to show the correct time in the relevant timezone

我对 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]])

详情为here

您有效地将您的配置传递给 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);

天哪,我在这上面浪费了太多时间,但最终我意识到这是我代码中的错字。任何有同样问题的人确保使用 timeZone 而不是 timezone