最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Subtracting a week from firebase.firestore.Timestamp.now()? - Stack Overflow

programmeradmin1浏览0评论

How would I go about subtracting a week from a firebase.firestore.Timestamp.now() timestamp? I have different documents that have a timestamp, and I need to build a function that would check if any of those documents have a timestamp older than 7 days. Heck, maybe there is a built in function to check if a date is "expired"? Thanks in advance.

How would I go about subtracting a week from a firebase.firestore.Timestamp.now() timestamp? I have different documents that have a timestamp, and I need to build a function that would check if any of those documents have a timestamp older than 7 days. Heck, maybe there is a built in function to check if a date is "expired"? Thanks in advance.

Share Improve this question asked Mar 1, 2021 at 14:07 MicasiOMicasiO 1491 gold badge2 silver badges10 bronze badges 1
  • depends on the precision, but you could just take the seconds from the timestamp and subtract a week (604800)? Or use the builtin toDate() firebase.google./docs/reference/js/… method and a library like date-fns to pare the javascript date objects? – Thomas Kuhlmann Commented Mar 1, 2021 at 14:15
Add a ment  | 

1 Answer 1

Reset to default 10

As defined here,

firebase.firestore.Timestamp.now()

is the equivalent of

firebase.firestore.Timestamp.fromMillis(Date.now())

To get a week old timestamp, you would use:

// 1 week in ms = 1000 * 60 * 60 * 24 * 7 = 604800000

const nowTimestamp = firebase.firestore.Timestamp.now();
const weekOldTimestamp = firebase.firestore.Timestamp.fromMillis(nowTimestamp.toMillis() - 604800000);
// or the shorter
const weekOldTimestamp = firebase.firestore.Timestamp.fromMillis(Date.now() - 604800000);

Let's say you have the following document in a collection called /photos:

{
  "title": "My Photo",
  "desc": "This is the first photo I uploaded here",
  "storageRef": "/userData/userid1/uploads/89q24u2q98y23.png",
  "thumbnailRef": "/userData/userid1/uploads/89q24u2q98y23.thumbnail.png",
  "createdAt": FieldValue.serverTimestamp(),
}

If you wanted to find all photos that were older than a week, you would use, either of the following identical statements:

firebase.firestore().collection("photos")
  .where("createdAt", "<", new Date(Date.now() - 604800000))
  .get()

or

const weekAgoTimestamp = firebase.firestore.Timestamp.fromMillis(Date.now() - 604800000);

firebase.firestore().collection("photos")
  .where("createdAt", "<", weekAgoTimestamp)
  .get()

If you had copy of the document already, from a query like this:

const aPhotoSnapshot = await firebase.firestore()
  .doc("photos/somePhotoId")
  .get();

and you wanted to check if it was older than a week, you would use:

const createdAtTimestamp = aPhotoSnapshot.get("createdAt");
const isWeekOld = createdAtTimestamp.toMillis() < Date.now() - 604800000;
发布评论

评论列表(0)

  1. 暂无评论