第1步:我正在从气象服务提供商那里读取信息,他们在Unix和UTC中提供日出时间-类似于“ 1565616151”
第2步:我正在使用“ var Sunrise = new Date(openWeatherData.sys.sunrise * 1000)”将其转换为Javascript Date
第3步:我需要将其作为时间戳存储在我的Firestore文档中。但是我无法转换第2步中的日期
我尝试使用:
admin.firestore.Timestamp.fromDate(sunrise)
这使我在控制台上出现以下错误
TypeError:无法读取未定义的属性“ getTime”
在Function.fromDate(/srv/node_modules/@google-cloud/firestore/build/src/timestamp.js:64:42)
相关代码:
request(url, (error, response, body) => {
if (response.statusCode === 200) {
console.log('Successfully retrieved from openweather');
var openWeatherData = JSON.parse(body);
console.log(`Output from OpenWeather for Sunrise:${openWeatherData.sys.sunrise}` );
var sunrise = new Date(openWeatherData.sys.sunrise*1000);
console.log(`Sunrise after conversion to JS Date:${sunrise}` );
}
else {
var openWeatherDataError = JSON.parse(body);
console.log('Issue fetching from open weathermap. Status code: ' + openWeatherDataError.cod
+ 'Message: ' + openWeatherDataError.message);
}
});
admin.firestore().collection('myCollectionPath')
.doc('myDoc')
.set(
{
'status': 'initiated',
'initiationTime': FieldValue.serverTimestamp(),
'sunrise': admin.firestore.Timestamp.fromDate(sunrise),
}
)
.then(doc => {
return res.status(200).send('Stored Successfully');
})
.catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to store', err });
});
}
);
预期结果:文档将成功保存在Firestore中
答案 0 :(得分:0)
第一件事是将将sunrise
写入Firestore 的代码移到设置sunrise
值的块中。
所以:
request(url, (error, response, body) => {
if (response.statusCode === 200) {
console.log('Successfully retrieved from openweather');
var openWeatherData = JSON.parse(body);
console.log(`Output from OpenWeather for Sunrise:${openWeatherData.sys.sunrise}` );
var sunrise = new Date(openWeatherData.sys.sunrise*1000);
console.log(`Sunrise after conversion to JS Date:${sunrise}` );
admin.firestore().collection('myCollectionPath')
.doc('myDoc')
.set({
'status': 'initiated',
'initiationTime': FieldValue.serverTimestamp(),
'sunrise': admin.firestore.Timestamp.fromDate(sunrise),
}).then(doc => {
return res.status(200).send('Stored Successfully');
})
.catch(err => {
console.error(err);
return res.status(404).send({ error: 'unable to store', err });
});
}
else {
var openWeatherDataError = JSON.parse(body);
console.log('Issue fetching from open weathermap. Status code: ' + openWeatherDataError.cod
+ 'Message: ' + openWeatherDataError.message);
}
});
});
如果这仍然给您带来问题,请检查获得的日志输出。