'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.
Solution 1:[1]
If you want to use setTimeOut, you need to:
- Compute the difference between the date chosen in the date picker and the current date. This will give you a duration.
- 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Araelath |
