Home > Software engineering >  How to check if a day has passed in Firebase?
How to check if a day has passed in Firebase?

Time:12-19

I have saved this timestamp in a Firestore document:

last_check_mmr: 14 dicembre 2021 15:39:01 UTC 1

How can I check if a day has passed from that date using Javascript?

CodePudding user response:

Since you use a Cloud Function it is quite easy by using Dayjs, the "minimalist JavaScript library that parses, validates, manipulates, and displays dates".

Something like the following, using the diff() method, should do the trick:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const dayjs = require('dayjs');

// Let's imagine you use a scheduled Cloud Funciton
exports.scheduledFunction = functions.pubsub.schedule('...').onRun(async (context) => {

  // Get the value of the timestamp, e.g. by fetching a Firestore document
  
  const docRef = ...;
  const snap = await docRef.get();

  const last_check_mmr = snap.get('last_check_mmr');
  
  const date = dayjs(last_check_mmr.toDate());
  const now = dayjs();

  console.log(date.diff(now, 'd'));

  // If you get a value of 0, it means it is less than a day, if you get -1 or less it is more than a day

  if (date.diff(now, 'd') < 0) {
     // more than a day
  }

  return null;

});
  • Related