I'm working on a Firebase Cloud Function that queries Firestore data based on date ranges provided in the request payload. However, I've encountered challenges with time zone conversions impacting the accuracy of the queried data. Specifically, Firestore stores timestamps in UTC, and I need to compare them with dates sent in the request payload, which might be in different time zones.
I've tried converting the incoming dates to Firestore Timestamps and using them in queries, but inconsistencies persist, especially with time zone differences.
What's the best approach to handle time zone conversions accurately within Cloud Functions when querying Firestore using Firestore Timestamps compared to dates sent in the request payload? How can I ensure the queried date range aligns correctly despite varying time zones?
Any insights, best practices, or alternative methodologies to handle this time zone conversion challenge in Firestore Timestamp-based queries within Cloud Functions would be greatly appreciated! Thanks in advance for your help!
The following is my code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.getExpenses = functions.https.onCall(async (data, context) => {
if (!context.auth.uid) {
return { error: 'Unauthorized' };
}
const requesterStartDateTime = new Date(data.startDate);
const requesterEndDateTime = new Date(data.endDate);
// Set the time boundaries for the start date to the beginning of the day
requesterStartDateTime.setUTCHours(0, 0, 0, 0);
// Set the time boundaries for the end date to the end of the day
requesterEndDateTime.setUTCHours(23, 59, 59, 999);
const shopId = data.shopId;
try {
const expensesSnapshot = await admin.firestore().collection('expensesRegister')
.where('shopId', '==', shopId)
.get();
const expenses = [];
for (const doc of expensesSnapshot.docs) {
const expenseName = doc.data().expenseName;
const expenseDocReference = doc.ref; // Reference to the expensesRegister document
const businessExpensesRef = expenseDocReference.collection('business_expenses');
const businessExpensesSnapshot = await businessExpensesRef
.where('date', '>=', requesterStartDateTime)
.where('date', '<=', requesterEndDateTime)
.get();
let totalAmount = 0;
businessExpensesSnapshot.forEach(expenseDoc => {
totalAmount += expenseDoc.data().amount;
});
expenses.push({
expenseName,
totalAmount,
expenseDocumentReference: '/expensesRegister/'+ expenseDocReference.id, // Include the reference here
});
}
return expenses; // Returning the array directly without a key
} catch (error) {
return { error: error.message };
}
});
my payload is in this format
{
"data": {
"startDate": "2023-12-4",
"endDate": "2023-12-04 23:59:59.999",
"shopId": "60322786"
}
}