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)
Related
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)
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
I am trying to use Tampermonkey to find a UTC time offset and return it as as a time. The website shows an offset which I pull here
waitForKeyElements (".UTCText", getTZ_Offset);
which returns a string
console.log ("Found timezone offset: ", tzOffset);
usually like this 08:00 It can be + or -
Then i want to convert that into actual time. Eg if UTC time is 00:00, I would like to print a string "The users time is 08:00" if the offset was +08:00.
I thought i could use momentjs to get UTC time moment().utcOffset(tzOffset) and pass the offset.
When i do that it just returns NaN
What am I doing wrong?
Multiply the part before the : by 60, and add it to the second part:
const tzOffset = '08:00';
const [hourOffset, minuteOffset] = tzOffset.split(':').map(Number);
const totalMinuteOffset = hourOffset * 60 + minuteOffset;
console.log(totalMinuteOffset);
If the input may be negative, then check that as well:
const tzOffset = '-08:00';
const [_, neg, hourOffset, minuteOffset] = tzOffset.match(/(-)?(\d{2}):(\d{2})/);
const totalMinuteOffset = (neg ? -1 : 1) * (hourOffset * 60 + Number(minuteOffset));
console.log(totalMinuteOffset);
A few time zones differ from UTC not only by hours, but by minutes as well (eg, UTC +5:30, UTC +9:30), so just parseInt, even if it worked, wouldn't be reliable everywhere.
I want to compare two dates with time and i want if time difference more than one minute then expire message should display otherwise verify message should display.How can i do this here is my code
var dateFormat = require('dateformat');
var day=dateFormat(new Date(date), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:02:27
var currenttime=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:08:48
var compare = day - currenttime;
console.log(compare);
Using a JavaScript Date object you can use Date.valueOf() to get the milliseconds from the epoch of that time and then do plain subtraction to get the difference. If it is greater than 60000 then expire.
// I swapped your values on either side of the subtraction operator
// to prevent a negative time difference
var compare = currentTime.valueOf() - day.valueOf()
var isExpired = compare >= 60000
console.log('isExpired', isExpired)
You can compare after generating timestamp of both time. Few ways to generate timestamp
1) +new Date()
2) https://momentjs.com/
Example using moment js :
var compare = moment().format('X') - moment("1995-12-25").format('X'); // In seconds
I have a unix timestamp: 1368435600. And a duration in minutes: 75 for example.
Using javascript I need to:
Convert the timestamp to a string format hours:mins (09:00)
Add n minutes to the timestamp: timestamp + 75mins
I tried the moment.js library:
end_time = moment(start_time).add('m', booking_service_duration);
booking_service_duration was 75 but it added an hour. I'd also rather not have to use another js library
To add 75 minutes, just multiply by 60 to get the number of seconds, and add that to the timestamp:
timestamp += 75 * 60
To convert to hours:mins you will have to do a bit more math:
var hours = Math.floor(timestamp/60/60),
mins = Math.floor((timestamp - hours * 60 * 60) / 60),
output = hours%24+":"+mins;
Unix time is the number of seconds that have elapsed since 1 January 1970 UTC.
To move that time forward you simply add the number of seconds.
So once you have the minutes, the new timestamp is oldTime + 60*minutes
For the conversion look up parsing libraries, there is code out there for this, do some research.
So you want to convert a timestamp you have, timestamp, to locale time string after adding some time interval, specifically minutes, to it.
Whether you have a kind of date-time string or a kind of epoch mili/seconds, just create a Date object:
const date = new Date(timestamp);
Keep in mind since what you need to do require to add/substract some numbers (your case: minutes) to another number, not some date object or some date-time string, and that number is the epoch mili/secods of your date. So, always you will need the number representation of your date in mili/seconds. JavaScript Date.prototype.getTime() does return epoch miliseconds of your date. Use it:
const miliseconds = date.getTime();
Add as many as miliseconds to it:
const newMiliseconds = miliseconds + (75 * 60 * 1000);
After that, as you said you need a date-time string, well a portion of it; locale time string, you will need to go all the way back; from numbers to date object and to a date-time string:
const newDate = new Date(newMiliseconds);
const newTimestamp = newDate.toString();
Or instead of getting the whole string of it, use the following specialized method to get the format/portion of the string representation of the date object that you like directly:
const newTimestamp = newDate.toLocaleTimeString(); // "12:41:43"
Finally, all you have to do is to just strip the last semicolon and seconds to get hours:minutes format:
const newHoursMins = newTimestamp.slice(0, -3);
Better make a function of it:
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
I left the final formatting out here. You can use this for substraction as well by pasing a negative second argument. Note the seconds argument is in miliseconds and unix timestamp varies and might given to you as seconds instead, in which case you will need to convert it to miliseconds or change the above funciton definition.
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
console.log("new Date(1368435600*1000).toLocaleTimeString(): ", new Date(1368435600*1000).toLocaleTimeString())
console.log("timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleString): ", timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleTimeString))
Apart from what you need, for last parameter, toStringFunc, your options vary and encompasses all related Date methods, the are on Date.prototype:
toString
toDateString
toTimeString
toLocaleString
toLocaleDateString
toLocaleTimeString
toIsoString
toUTCString
toGMTString
toJSON