如何在时间戳中增加天数?

时间:2019-06-02 18:36:38

标签: javascript typescript google-cloud-functions

我有一个开始日期时间戳记和一个持续时间(天数),我需要获取结束日期,我对这段代码感到厌倦,因为给出了错误的结束日期时间戳记

exports.terminateStoreAd = functions.https.onRequest(async(req, res) => {
        try {
            const snapshot =await admin.database().ref("StoreAds").once("value");
            if (snapshot.exists()) {
                snapshot.forEach(snapData => {
                    if (snapData.exists()) {
                        const endDate=new Date(snapData.val().startDate).getTime()+(snapData.val().duration*24*60*60*1000);
                        res.send(""+endDate);
                    }
                });
                res.send("done")
            }
        } catch (error) {
            console.log("terminateStoreAd error :" + error.message); 
        }
    });

我的开始日期是:1559449773

持续时间:5

结束日期:1991449773:(

提前谢谢。

3 个答案:

答案 0 :(得分:0)

给出开始日期为2019-05-01,然后5天后,只需使用参数化版本创建新日期即可。

请注意,该月的索引为零,因此5月的第5个月的索引为4。由于我想在5月1日之后的5天使用1+5作为一天:

const startDate = new Date(2019, 4, 1);
const endDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()+5);

console.log(`Start Date: ${startDate}, End Date: ${endDate}`);
console.log(`Start Date: ${startDate.valueOf()}, End Date: ${endDate.valueOf()}`);

答案 1 :(得分:0)

const endDate = snapData.val().startDate + snapData.val().duration*24*60*60*1000;

足以获取所需的日期(以毫秒为单位)(如果startDate以毫秒为单位)

否则,如果startDate是日期字符串,

const endDate = (new Date(snapData.val().startDate)).getTime() + snapData.val().duration*24*60*60*1000;

假设您需要endDate以毫秒为单位。

答案 2 :(得分:0)

最终我找到了解决方案

exports.terminateStoreAd = functions.https.onRequest(async(req, res) => {
try {
    const snapshot =await admin.database().ref("StoreAds").once("value");
    const promises = [];
    if (snapshot.exists()) {
        snapshot.forEach(childSnapshot => {
            const endDate=childSnapshot.val().startDate + childSnapshot.val().duration  * 86400;
            const today=Math.round(new Date().getTime()/1000);
            if (endDate <= today) {
                promises.push(
                    admin.database().ref("StoreAdsHistory").child(childSnapshot.key).set(childSnapshot.val()),
                    childSnapshot.ref.remove(),
                    res.send()
                );
            }
        });
       } 
       await Promise.all(promises);
    }catch (error) {

}

});

相关问题