如何检查 Firebase 是否过了一天?
How to check if a day has passed in Firebase?
我已将此时间戳保存在 Firestore 文档中:
last_check_mmr: 14 dicembre 2021 15:39:01 UTC+1
如何使用 Javascript 检查该日期是否已经过了一天?
由于您使用 Cloud Function,因此使用 Dayjs
“解析、验证、操作和显示日期的极简主义 JavaScript 库”非常容易。
像下面这样的东西,使用 diff()
方法,应该可以解决问题:
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;
});
我已将此时间戳保存在 Firestore 文档中:
last_check_mmr: 14 dicembre 2021 15:39:01 UTC+1
如何使用 Javascript 检查该日期是否已经过了一天?
由于您使用 Cloud Function,因此使用 Dayjs
“解析、验证、操作和显示日期的极简主义 JavaScript 库”非常容易。
像下面这样的东西,使用 diff()
方法,应该可以解决问题:
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;
});