Reputation: 280
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?
Upvotes: 2
Views: 1674
Reputation: 4243
according to Date.parse() is only ISO 8601 format of ECMA262 string supported, so use:
new Date("2022-11-16T12:00:00Z")
new Date(2022,10,16,12)
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 behaviourconst 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 });
Upvotes: 3
Reputation: 980
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.
Upvotes: 1
Reputation: 280
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)
Upvotes: 0