How do i get remaining seconds of future date in javascript - 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)

Related

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 can I substract hours from my date using data from a string?

I have a date in UTC in javascript, and I would like to substract some hours.
I searched online and apparently I should concat the substraction to the date like the following:
const diff = "-5"
const utcDate = "2017-02-22 17:28:13"
const date = new Date(utcDate + diff[0] + ' ' + diff[1])
//desired output: 2017-02-22 12:28:13
But I can't seem to make it work.
I do all my Date calculations with .getTime().
So an hour is 3600000 milliseconds.
const MILLISECONDS_HOUR = 3600000;
const diff = -5;
const utcDate_str = "2017-02-22 17:28:13";
const utcDate = new Date( utcDate_str );
const minus_5_hours = new Date( utcDate.getTime() + ( MILLISECONDS_HOUR * diff ));
console.log( utcDate.toJSON());
console.log( minus_5_hours.toJSON());
The big advantage is that javascript will take care of leap years, month boundaries and such.
But since you are calling your variable diff, are you trying to calculate lcoal time vs UTC time?
In that case, reread the javascript Date methods. There's a bunch of methods to handle both UTC and local time, for example: date.getUTCDate() and date.getDate().
So you might not have to calculate all of this yourself.
Also, if you format your dates according to the ISO, "2017-02-22T17:28:13.000Z", this will automatically get parsed as UTC.
someDate.setHours(someDate.getHours()+1);
From https://stackoverflow.com/a/1050782/537998

setHours is not a function when converting time from string

I am trying to compare a time in string format to the current time. I've tried setting up two Date objects and calling .Now() on both of them, then on one of them adjusting the time to the time that is in string format by splitting it and parsing both the hours and minutes to integers, but I get the following error:
setHours is not a function
The 'cutoff' value I'm using is '15:00' and when following in the debugger I can see this splits in to split[0] = 15 and split[1] = 00 (this is before they are parsed into integers.
var cutoff = data.CutOff;
var split = cutoff.split(":");
var today = Date.now();
var hours = parseInt(split[0]);
var min = parseInt(split[1]);
today.setHours(hours, min);
if (Date.now() < today) {
// Do Something
}
You want to do new Date() as opposed to Date.now()
new Date creates a Date instance which allows you to access the Date methods.
Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Javascript: how to add n minutes to unix timestamp

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

Categories