MOAZ ALI
MOAZ ALI

Reputation: 37

Convert Material-UI DatePicker value to seconds

React Material-Ui datepicker currently gives me value like this: 2021-05-26T01:30 How can I convert it to seconds?

PS: I am building a schedule SMS module. So my plan is to convert the selected date into seconds so that I can then use setTimeOut() to send the SMS when the day & time arrives.

Upvotes: 0

Views: 791

Answers (1)

Araelath
Araelath

Reputation: 595

If you want to use setTimeOut, you need to:

  1. Compute the difference between the date chosen in the date picker and the current date. This will give you a duration.
  2. Convert the duration into millisecond as the delay for setTimeOut is specified in milliseconds

To do so the easiest way is probably to use dayjs, which is a lightweight package to handle Date & Time operations. It works well with react because it is immutable.

Using dayjs.diff you can compute the duration in milliseconds directly like so : const durationInMs = daysj("2021-05-26T01:30").diff(dayjs())

note: By default dayjs parses datetime in local time

Edit

You can also use the Native Date Constructor directl, here's an example from the docs:


// Using built-in methods
let start = new Date()
let end = new Date("2021-05-26T01:30")

let elapsed = end.getTime() - start.getTime() // elapsed time in milliseconds

Upvotes: 1

Related Questions