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.
-
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
1 Answer
Reset to default 10As 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;