Javascript:评估UTC与中欧时间之间的差异

时间:2019-03-07 11:02:19

标签: node.js datetime google-cloud-functions timezone-offset

我在Firebase云功能中有一个服务器应用程序,它具有从第三方API接收数据的webhooks。 在这些数据中,我用HH:mm当地时间(中欧时间)表示时间。 我需要将它们作为时间戳UTC存储在Firestore中。

我尝试过:

         //Evaluate offset between CET and UTC
        const dAujourdhui = new Date(); //07/03/2019 10:39 (UTC)
        const nHeureUTC = dAujourdhui.getUTCHours(); //10
        const nHeureLocal = dAujourdhui.getHours();  //10
        const timeZoneOffset = nHeureUTC - nHeureLocal //0!

         // Build a timestamp based on today's date and received time
        const currentDateString = dateFormat(dAujourdhui, "yyyy-mm-dd");
        var estimatedDateTimeOfArrival = new Date(`${currentDateString} ${timeReceivedFrom3rdPartyAPI}`);

         // Add offset to hours
        const utcHour = estimatedDateTimeOfArrival.getUTCHours()
        estimatedDateTimeOfArrival.setHours(utcHour + timeZoneOffset)

        // Save to firestore
        ...

如您所见,由于代码在UTC中设置的服务器中运行,因此我无法评估CET与UTC之间的偏移量。

有什么解决办法的想法吗?

1 个答案:

答案 0 :(得分:0)

这是我找到的解决问题的方法。 它基于一个外部库:'moment-timezone'

        // Example's initial setup
        const dateFormat = require('dateformat')
        const moment = require('moment-timezone');
        const timeReceivedFrom3rdPartyAPI = "14:30" // Format "HH:mm", Paris time

        // Construct Date object with today's date and timeReceivedFrom3rdPartyAPI
        const currentDate = new Date();
        const currentDateString = dateFormat(currentDate, "yyyy-mm-dd");
        const estimatedDateTimeOfArrival = moment.tz(`${currentDateString} ${timeReceivedFrom3rdPartyAPI}`, "Europe/Paris").toDate()

        console.log(estimatedDateTimeOfArrival)
        // 08/03/2018 13:30 UTC
        // Now I have UTC Full Date corresponding to timeReceivedFrom3rdPartyAPI