Nasyx Nadeem
Nasyx Nadeem

Reputation: 280

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?

Upvotes: 2

Views: 1674

Answers (3)

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 });

Upvotes: 3

pope_maverick
pope_maverick

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

Nasyx Nadeem
Nasyx Nadeem

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

Related Questions