firebase cloud functions UTC time is off by four hours.
Im working on a react-native app for debating. I am working on getting each case to close by comparing the completion time to the time now. I am using a firebase cloud function to do this. The function was working perfectly last week however when i started working on the app this week the function was consolelogging the wrong time and when i do the same calculation from my app running on my computer it is correct so i can rule out how im calculating it!
const date = require('date-and-time');
const now = new Date()
const currentDate = date.format(now, 'MM/DD/YYYY, HH:mm:ss')
const dateFrom = userCase.completionTime
const DateDiff = require('date-diff')
const date1 = new Date(dateFrom)
const date2 = new Date(currentDate)
const difff = new DateDiff(date1, date2)
const time = difff.seconds()
const totalyesVotes = _.size(yesVotes)
const totalnoVotes = _.size(noVotes)
console.log(currentDate + "current time")
so i console.logged these at the same time this one from google cloud
05/06/2019, 20:50:49
and this one from my computer
05/06/2019, 16:50:49
Related
I have been trying to use Luxon to get (for comparison reasons) the epoch miliseconds from two DateTimes in different timezone.
I'm using the .valueOf() method to do so, but even that I'm setting the different timezones for each DateTime, that method always return the same value:
const { DateTime } = require('luxon')
const dtString = '2022-01-15 13:00:00'
const d1 = DateTime.fromSQL(dtString).setZone('America/Sao_Paulo').valueOf()
const d2 = DateTime.fromSQL(dtString).setZone('America/New_York').valueOf()
console.log(d1) // logs 1642262400000
console.log(d2) // logs 1642262400000 (same)
What is wrong?
Instead of parsing the dates in one zone and then shifting the times around, just parse them in the zone you want:
const dtString = '2022-01-15 13:00:00';
const d1 = DateTime.fromSQL(dtString, { zone: "America/Sao_Paulo" }).valueOf();
const d2 = DateTime.fromSQL(dtString, { zone: "America/New_York" }).valueOf();
d1 //=> 1642262400000
d2 //=> 1642269600000
The difference there is that in yours, Luxon parses the string using your system zone. Then you change the zone, but the time is still the time, unless you use keepLocalTime. In mine, I'm telling Luxon what zone to use in interpreting the string, which results in a different time being computed for the two cases.
Based on this Luxon issue, I found the fix for that:
We should use the keepCalendarTime: true option in the setZone method to make it work.
That extra flag says "yes, change the actual time"
So the functional code looks like:
const { DateTime } = require('luxon')
const dtString = '2022-01-15 13:00:00'
const opts = { keepCalendarTime: true }
const d1 = DateTime.fromSQL(dtString).setZone('America/Sao_Paulo', opts).valueOf()
const d2 = DateTime.fromSQL(dtString).setZone('America/New_York', opts).valueOf()
console.log(d1) // logs 1642262400000
console.log(d2) // logs 1642269600000 (prints different value)
I want to get date range between start_time and end_time.
var newrange = sails.moment.range(start_time, end_time);
But it says,
TypeError: sails.moment.range is not a function
Try setting up the imports like below and then run the function:
const moment = require("moment");
const momentRange = require("moment-range");
momentRange.extendMoment(moment);
var newrange = moment.range(start_time, end_time);
I am trying to convert my Time string that displays in my app as 11:00. I need to convert to a timestamp so I can replace the current Time field in my firestore which is a timestamp.
I have tried using moment.js to update the field but it changes the data type to a string.
Current value in my firestore is shown below
submitJob = () => {
const { navigation } = this.props;
const customer_jobnumber = navigation.getParam('JobNumber', 'No Job Number');
const customer_starttime = navigation.getParam('datetime', 'No Job Start Time');
const customer_end = navigation.getParam('datetimefinish', 'No Job Finish Time');
firebase.firestore().collection("jobs").doc(customer_jobnumber).update({ endtime: customer_end, starttime: customer_starttime, value: firebase.firestore.FieldValue.serverTimestamp() });}
The desired value would be - October 4, 2020 at 11:00:00 AM UTC+1
Found the solution with this, if anyone comes across the same problem.
let tx = customer_starttime.split(":")
let dx = new Date().setHours(parseInt(tx[0]),parseInt(tx[1]),0)
let dl = new Date(dx)
So I have implemented Stories in my Flutter+Firebase app, and wrote a Cloud Function in JS to delete all stories older than 24h. I added a test Story in the Database, with a field 'timestamp' and set it to August 25, 8:00. Now when I am running the function, I print out the document id and the timestamp of that found document. However, the dates that get printed out are all in 1973!?
Here is my function:
// Start delete old Stories
const runtimeOpts = {
timeoutSeconds: 300,
memory: '512MB'
}
const MAX_CONCURRENT = 3;
const PromisePool = promisePool.PromisePool;
exports.storiesCleanup = functions.runWith(runtimeOpts).pubsub.schedule('every 1 minutes').onRun(
async context => {
console.log('Cleaning stories...');
await getOldStories();
//const promisePool = new PromisePool(() => deleteOldStories(oldStories), MAX_CONCURRENT);
//await promisePool.start();
console.log("finished cleaning stories");
}
);
async function getOldStories() {
const yesterday = Date.now() - 24*60*60*1000;
console.log("Yesterday: " + yesterday);
var storyPostsRef = admin.firestore().collection("StoryPosts");
var query = storyPostsRef.where("timestamp", "<", yesterday);
storyPostsRef.get().then(
querySnapshot => {
querySnapshot.forEach(
(doc) => {
// HERE I AM PRINTING OUT!
console.log("Found document: " + doc.id + ", which was created on: " + doc.data().timestamp);
//doc.ref.delete();
}
)
return null;
}
).catch(error => {throw error;});
}
//End delete old stories
Here is a picture of a document and its timestamp:
And this is a picture of the id and timestamp printed out for that document:
Edit: So for printing out, I figured that if I print doc.data().timestamp.seconds I get the correct number of seconds since epoch. But I still don't understand what the number 06373393200.000000 (printed in the picture above) is. And how do I then make a query when I want to get all stories where the timestamp is small than today-24h ?
var query = storyPostsRef.where("timestamp", "<", Timesstamp.fromDate(yesterday)); does not work.
If you come to the conclusion that the printed timestamp is from a year other than the one shown in the console, then you are misinterpreting the output. Firestore timestamps are represented with two values - an offset in seconds since the unix epoch, and another offset in nanoseconds from that time. This much is evident from the API documentation for Timestamp.
You're probably taking the seconds offset value and interpreting as an offset in milliseconds, which is common in other timestamp systems. You can see how this would cause problems. If you want to take that a Firestore offset in seconds and use a tool to interpret it in a system that uses milliseconds, you will need to first multiply that value by 1,000,000 to convert seconds to milliseconds.
I am using 'rrule.js' library in node to parse my RRule. I would like to know if current day is same as rule day. It works on most cases but not all. I also use moment.js to compare. The issue is in "rule.after()". It should include the current day but it doesn't.
function checkIfToday(rruleStr){
var RRule = require('rrule').RRule;
var moment = require('moment');
var rule = RRule.fromString(rruleStr);
// Convert all dates into UTC before comparison
var todayutc = moment().utc(); // today in UTC
var nextOccurrence = rule.after(todayutc,inc=true); // next rule date including today
var nextOccurutc = moment(nextOccurrence).utc(); // convert today into utc
var match = moment(nextOccurutc).isSame(todayutc, 'day'); // check if 'DAY' is same
return match;
}
Any idea what's the best way to do this.
Thanks.
This worked for me. Try setting the time of todayutc back to the beginning of the day using moment's startOf method:
function checkIfToday(rruleStr){
var RRule = require('rrule').RRule;
var moment = require('moment');
var rule = RRule.fromString(rruleStr);
// Convert all dates into UTC before comparison
var todayutc = moment().utc().startOf('day'); // today in UTC
var nextOccurrence = rule.after(todayutc, true); // next rule date including today
var nextOccurutc = moment(nextOccurrence).utc(); // convert today into utc
var match = moment(nextOccurutc).isSame(todayutc, 'day'); // check if 'DAY' is same
return match;
}