Javascript-如何从Firebase Firestore时间戳中减去几个月?

时间:2018-07-16 23:23:48

标签: javascript firebase timestamp google-cloud-firestore

如何从admin.firestore.FieldValue.serverTimestamp()中减去日期?

假设我想知道5个月前的日期。

通过使用new Date() Javascript对象,我可以得到以毫秒为单位的日期。

我想将其保存为Firestore数据库中的时间戳。我该怎么办?

更新

我使用此功能发现日期:

function findBirthdate(age){
    var monthsAgo; 
    switch(age){
       case "_6months":
           monthsAgo = 3;
           break;
       case "6_12months":
           monthsAgo = 9;
           break;
       case "12_18months":
           monthsAgo = 15;
           break;
       case "18_24months":
           monthsAgo = 21;
           break;
       case "24_months":
           monthsAgo = 28;
           break;
       default:
           return;
   }

   var now = new Date();
   return now.setMonth(now.getMonth() - monthsAgo);
}

因此,我像在

中一样,致电var birth = findBirthdate(age)并将birth发送到Firestore

admin.firestore()....update({ birthdate: birth }).then(...

1 个答案:

答案 0 :(得分:0)

当我这样做

var date = new Date(); 
date.setMonth(date.getMonth() - 3); 
console.log(date);

它打印

  

2018年4月17日星期二21:11:19 GMT-0700(太平洋夏令时间)

区别在于您从setMonth返回结果,该结果恰好是时间戳。来自MDN documentation on setMonth()

  

返回:UTC 1970年1月1日00:00:00与更新日期之间的毫秒数。

由于要返回实际日期,因此需要执行以下操作:

var now = new Date();
now.setMonth(now.getMonth() - monthsAgo);
return now;