my problem:
I have 1 computer that sends data (also timestamp) to some firebase collection, let׳s say – Las Vegas, Nevada.
When Im trying to fetch data on my firebase functions I get the Timestamp property in GMT.
and my firebase function׳s propose is to return to frontend all Timestamps occur on specific day of the week, eventually I should get 7 days of the week with timestamps on each day.
my problem is to get GMT time and return the time based on clients location/timezone
on each timestamp from the collection so I can show it on a graph on the client side.
the status now: is I get timestamps that occur on Sunday, but I know that nothing happend on Sunday for sure.
no matter what I have tried, nothing helps.. I will be glad for some help 🙂
code below.
/////util functions:
const exposeDayName = (date) => {
return new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(date);
}
const fillMissingDays = (countObject) => {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const today = days.indexOf(exposeDayName(new Date()));
const fullWeekCount = {};
for (let i = today + 1; i < (days.length + today + 1); i++) {
const indexDay = i < 7 ? i : i - 7;
fullWeekCount[days[indexDay]] = countObject[days[indexDay]] ? countObject[days[indexDay]] : 0;
}
return fullWeekCount;
}
/////
const getAllWeeklySessionsDividedByDays = async (req, res) => {
try {
//function i have tried to solve this problem with no success.
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", { timeZone: tzString }));
}
let timezone = req.body.timezone;
let id = req.body.id;
const currentDate = new Date();
const previousWeekDate = new Date(currentDate.getTime() - 6 * 24 * 60 * 60 * 1000);
const conversationRef = db.collection("conversation");
const sessionsArr = [];
const snapshot = await conversationRef
.where('id', '==', Id)
.where("timestamp", ">=", previousWeekDate)
.where("timestamp", "<=", currentDate)
.get();
snapshot.forEach(doc => {
const element = doc.data();
sessionsArr.push({
Id: element.id,
sessionId: element.session_id,
timestamp: exposeDayName(element.timestamp.toDate())
});
});
const uniqueSessionsArr = [...new Map(sessionsArr.map(v => [JSON.stringify(v), v])).values()];
const countSessionsPerDay = {};
uniqueSessionsArr.forEach(session => {
const day = session.timestamp;
countSessionsPerDay[day] = countSessionsPerDay[day] ? countSessionsPerDay[day] + 1 : 1;
});
const fullWeekSessionsPerDay = fillMissingDays(countSessionsPerDay);
const result = {
labels: Object.keys(fullWeekSessionsPerDay),
datasets: [
{
label: "Daily Sessions",
data: Object.values(fullWeekSessionsPerDay)
},
],
}
res.status(200).send(result);
} catch (err) {
res.status(400).send(err.message);
}
}