Home > Mobile >  How do i get remaining seconds of future date in javascript
How do i get remaining seconds of future date in javascript

Time:11-16

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?

CodePudding user response:

  • 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

const secondsInTheFuture = new Date("11/16/2022 12:00:00").getTime() / 1000;
const secondsNow = new Date().getTime() / 1000;
const difference = Math.round(secondsInTheFuture - secondsNow);

console.log({ secondsInTheFuture, secondsNow, difference });

CodePudding user response:

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)

CodePudding user response:

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.

  • Related