我在Firebase云功能中有一个服务器应用程序,其中webhooks从第三方API接收数据。在这些数据中,我有时间用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
...
如您所见,我无法评估CET和UTC之间的偏移,因为代码是在UTC中设置的服务器中运行的。
关于如何解决它的任何想法?
这是我发现解决问题的解决方案。它基于外部库:'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