Reputation: 361
When printing the new Date()
object out I get the correct date Wed Jul 14 2021 02:29:46 GMT+0000 (Coordinated Universal Time)
, of course I have to adjust it for the timezone I need. But when I use methods to get the month, day and year the day and month values are wrong. I log out the output into the Firebase Functions logs. I tried the getFullMonth()
and getUTCMonth()
methods, but both give incorrect results. Why is it that the Date()
object is giving correct results but the methods are not?
exports.checkDailyRewards = functions.https
.onRequest(async (req, res) => {
const userId: string = req.query.id!.toString();
const userProfileRef = db.collection("users").doc(userId);
const currentDateObj = new Date();
const otherDate = Date.now();
console.log("other date: " + otherDate);
console.log("current date object: " + currentDateObj);
const year = String(currentDateObj.getFullYear());
let month = String(currentDateObj.getMonth());
let day = String(currentDateObj.getDay());
console.log("month: " + currentDateObj.getMonth());
console.log("day: " + currentDateObj.getDay());
if (month.length == 1) {
month = "0" + month;
}
if (day.length == 1) {
day = "0" + day;
}
const currentDateStr = year + "-" + month + "-" + day;
console.log("currentDateStr: " + currentDateStr);
const userDailyRewardsResult = await userProfileRef
.collection("daily_rewards").doc(currentDateStr).get();
if (userDailyRewardsResult.exists) {
console.log("reward already received");
res.status(200).send({dailyRewardReceived: "false"});
} else {
console.log("reward not received today");
const rewardData = {
experience: "5",
currency: "5",
};
userProfileRef.collection("daily_rewards")
.doc(currentDateStr)
.set(rewardData);
res.status(200).send({
dailyRewardReceived: "true",
rewardData,
});
}
});
As shown in the screenshot, the month: 6
and day: 3
values are wrong.
Upvotes: 0
Views: 42
Reputation: 3026
The JavaScript getMonth() and getUtcMonth() functions return a value ranging 0-11. This means you'll need to add 1 to the value returned to get the month of the year in the range 1-12.
Additionally, you're using the getDay() function, which returns the day of the week from 0-6. What you actually want is getDate() which returns the date of the month between 1-31.
Upvotes: 1