Firebase Function to get UTC time - javascript

My Firebase Function code:
My question is inside the code below
exports.scheduledFunction= functions.pubsub.schedule('every 5 minutes').onRun((context) => {
var snapshot= firebase.doc(something/somethingID).get();
var timestamp=snapshot[‘timestamp’];
//my question begins here:
//how can I make this condition
if(timestamp(according UTC time)<Current UTC time){
//do something
}
});
And my firestore timestamp field:
18 February 2021 00:00:00 UTC +4
Thank you!

Firestore TimeStamp has two properties nanoseconds and seconds, we shall use any one for the comparison
var timestamp = snapshot[‘timestamp’];
// fetch seconds and convert it into milliseconds
var time_in_millis = timestamp._seconds * 1000
if(time_in_millis < Date.now()){
//do something
}
Date.now() - method returns the number of milliseconds of UTC time since Unix epoch

Related

How do i get remaining seconds of future date in javascript

So i have an API, which gives me date format like this 11/21/2022 19:00:00 what i need to do is i have to schedule notification for this datetime, but the problem is i am using react-native/expo which accepts the scheduling time in seconds.
How do i convert this datetime to seconds, i mean if today's date is 11/15/2022 12:00:00 and the date on which the notification should be scheduled is 11/16/2022 12:00:00 which means the future date in 1 day ahead of todays date, and 1 day is equal to 86400 seconds, which means i have to trigger notification after 86400 seconds. So how do i get the remaining seconds of the upcoming date?
Use .getTime()
function Date.prototype.getTime() returns number of milliseconds since start of epoch (1/1/1970)
get the number of milliseconds and divide it 1000 to seconds
subtract (round) and you have the difference
according to Date.parse() is only ISO 8601 format of ECMA262 string supported, so use:
new Date("2022-11-16T12:00:00Z")
or new Date(2022,10,16,12)
rather not n̶e̶w̶ ̶D̶a̶t̶e̶(̶"̶1̶1̶/̶2̶1̶/̶2̶0̶2̶2̶ ̶1̶9̶:̶0̶0̶:̶0̶0̶"̶)̶ that can lead to unexpected behaviour
const secondsInTheFuture = new Date("2022-11-16T12:00:00Z").getTime() / 1000;
const secondsNow = new Date().getTime() / 1000;
const difference = Math.round(secondsInTheFuture - secondsNow);
console.log({ secondsInTheFuture, secondsNow, difference });
You can get the epoch time in js with the function + new Date, if you are passing any date value, to new Date(dateValue), please make sure to stringify.
+ new Date
To get the diff b/w these two dates in seconds,
const initialDate = '11/15/2022 12:00:00'
const futureDate = '11/16/2022 12:00:00'
const diffInSeconds = (+ new Date(futureDate) - + new Date(initialDate)) / 1000
ps: epoch time is in milliseconds, hence dividing by 1000.
Solved using dayjs package
const dayjs = require("dayjs")
const d1 = dayjs("2022-11-15 13:00")
const d2 = dayjs("2022-11-16 12:00")
const res = d1.diff(d2) / 1000 // ÷ by 1000 to get output in seconds
console.log(res)

How to calculate difference between saved timestamp and current time

I saved a timestamp in this format .
So what I want to do now is calculate the difference between the current time and the saved timestamap in a JavaScript function. But I have no idea how to do that.
Hope anyone can help.
When you fetch the document, 'timestamp' field would be of type Timestamp and you can use seconds property and current timestamp to calculate the difference as shown below:
const snap = await getDoc(docRef);
const timeDiff = Date.now() - snap.data()?.time.seconds * 1000;
console.log(`Time Difference: ${timeDiff} ms`)
This is actually very easy to achieve. Most important to know is that the function Date.now() returns you the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
To get the duration between to timestamps is like "end - begin = duration".
Here is a code example:
// collect the first timestamp
const beginTimestamp = Date.now()
// here comes a for loop to consume some time, otherwise you will get 0 milliseconds
for (var i=0; i<10000; i++) {
"Some kind of string".split("").reverse().join("")
}
// collect the second timestamp
const endTimestamp = Date.now()
// subtract the first from the second timestamp tells you the milliseconds in between of both timestamps
console.log("Duration in milliseconds:", endTimestamp - beginTimestamp)

Convert JavaScript date to Swift JSON timeIntervalSinceReferenceDate format

Given a JavaScript date, how can I convert this to the same format as Swift JSON encoding?
e.g. I would like to get a value of 620102769.132999 for the date 2020-08-26 02:46:09
The default Swift JSON encoding outputs a value which is the number of seconds that have passed since ReferenceDate. https://developer.apple.com/documentation/foundation/jsonencoder/2895363-dateencodingstrategy
It seems ReferenceDate is 00:00:00 UTC on 1 January 2001.
https://developer.apple.com/documentation/foundation/nsdate/1409769-init
function dateToSwiftInterval(date: Date): number {
const referenceDate = Date.UTC(2001,0,1);
const timeSpanMs = (date - referenceDate);
return timeSpanMs / 1000;
}
const myDate = new Date(1598366769000);
console.log(dateToSwiftValue(myDate)); // 620102769
As Elwyn says, Swift represents dates as time intervals that are seconds since 1 Jan 2001 UTC. Javascript Dates use milliseconds since 1 Jan 1970 UTC, so all you need to do is adjust by the reference date difference and divide by 1000, e.g.
// Javascript function to convert a Date to a Swift time interval
// date is a Javascript Date, defaults to current date and time
function toSwiftTI(date = new Date()) {
return (date - Date.UTC(2001,0,1)) / 1000;
}
console.log(toSwiftTI());
Since the time difference is a constant, 978307200000, you might just use that instead of calculating it every time, so:
return (date - 978307200000) / 1000;
Going the other way, just multiply by 1,000 and add the constant:
function swiftToDate(ti) {
return new Date(ti * 1000 + 978307200000);
}
console.log(swiftToDate(620102769.132999).toISOString());

How to addition seconds with seconds in JavaScript?

I have my current time in seconds and duration time in seconds.
I want to add both seconds to calculate the end time of the song (for example).
But i have a weird format in the result.
Here is my code :
// This is my song's duration
var duration = new Date("Sept 21, 2019 00:03:32");
var durationSeconds = duration.getSeconds();
// Current second
var date = new Date();
var seconds = date.getSeconds();
var differenceSecondsConverted = date.setSeconds(seconds + durationSeconds);
console.log(differenceSecondsConverted);
And the result is something like : 1569102592740
Thanks
Actually the code works as it should, probably, you just miss some concept.
The new Date() is a constructor that returns an instance of Date object.
This object have several properties. When you instantiate it, it returns something like Sun Sep 22 2019 01:21:14 GMT+0200 (CEST) which is string representation of current time.
However, this string representation is not how JS actually "thinks" about the time.
Internally, "time" for JS is number of milliseconds passed from January 1, 1970, 00:00:00.
It looks something like this: 1569108461979.
You may see it if you run Date.now();
Also, if you do any calculations (not directly, but using methods like .setDate) with new Date(), it will be internally calculated as milliseconds passed from 1, 1970, 00:00:00.
So, the main problem in your code is that your duration variable is not actually "duration".
It just contains an object that represents Sept 21, 2019 00:03:32.
It is just a moment in time (3 minutes, 32 seconds after midnight of 20 of September 2019).
To calculate when the song will end if it starts right now, you'd do something like:
let now = Date.now();
// Song duration in milliseconds
let songDuration = 201000;
let songEndTime = now + songDuration;
console.log( new Date(songEndTime) );
You can get a date object for the time in say 3:32 by adding 3 minutes and 32 seconds to the current date, e.g.
// time is minutes and seconds as mm:ss
function nowPlus(time) {
let [m, s] = time.split(':').map(Number);
let now = new Date();
now.setMinutes(now.getMinutes() + m, now.getSeconds() + s);
return now;
}
console.log('In 3:32 it will be: ' + nowPlus('3:32').toLocaleString(undefined, {hour12:false, hour: 'numeric', minute:'2-digit', second:'2-digit'}));

Reset timezone aware timestamp momentjs

I am using momentjs for doing my date operations and want to code a scenario where if timestamp is given, and timezone name is given, then I want to reset the time to midnight. For e.g.
let timestamp = 1493638245234;
expect(new Date(timestamp).toISOString()).toBe('2017-05-01T11:30:45.234Z'); // Time in UTC
let truncatedTimestamp = functionName(timestamp, 'America/Los_Angeles');
console.log(truncatedTimestamp);
expect(new Date(truncatedTimestamp)).toBe('2017-05-01T04:00:00.000Z');
const functionName = (timestamp, timezone) => {
return moment
.tz(timestamp, timezone)
.startOf('day')
.toDate()
.getTime();
};
I would like the function 'functionName' to return midnight of America/Los_Angeles time and not in UTC.
The timestamp I entered is 5th May 2017, 11:30 AM UTC.
I expect the function to return me timestamp for 5th May 2017, 00:00 America/Los_Angeles (Since 5th May 2017 11:30 AM UTC will be 11:30 AM -7 hours in America/Los_Angeles.) and convert it to milliseconds.
You have to remove toDate() that gives a JavaScript date object using local time. Then you can use valueOf() instead of getTime().
moment#valueOf simply outputs the number of milliseconds since the Unix Epoch, just like Date#valueOf.
Your code could be like the following:
const functionName = (timestamp, timezone) => {
return moment(timestamp)
.tz(timezone)
.startOf('day')
.valueOf();
};
let timestamp = 1493638245234;
let truncatedTimestamp = functionName(timestamp, 'America/Los_Angeles');
console.log(truncatedTimestamp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.17/moment-timezone-with-data-2012-2022.min.js"></script>
Note that moment.tz and tz() are equivalent in your case (since you are passing millis).
I modified my function functionName to be like this and it worked.
const functionName = (timestamp, timezone) =>
moment
.tz(timestamp, timezone)
.startOf('day')
.valueOf();
NOTE: Some user posted this answer, but they deleted their answer.

Categories