简体   繁体   中英

Covert date to epoch timestamp using Javascript

I have date in MM/DD/YYYY HH:MM AM/PM format Example 07/27/2022 10:36 AM I want to convert it into Epoch timestamp which is 1658898360

The Date object in Javascript is notoriously tricky to work with, and date parsing is sadly lacking. Simply using

const dateString = "07/27/2022 10:36 AM"
const date = new Date(dateString)

might work, but not reliably.

One option is to use the date-fns library :

import { parse, getUnixTime } from 'date-fns'

const date = parse('07/27/2022 10:36 AM', 'MM/dd/yyyy hh:mm a', new Date())
const epoch = getUnixTime(date)

You can use the date.getTime method to convert it to epoch:

 const date = new Date("07/27/2022 10:36 AM"); console.log(date.getTime() / 1000)

Just be sure that you (or the client) is in the same timezone you are expecting (IST in this case).

Or just add GMT+5:30 to ensure this.

 const date = new Date("07/27/2022 10:36 AM GMT+5:30"); console.log(date.getTime() / 1000)

You can use below sample code:

 function epoch (date) { return Date.parse(date) } const dateToday = new Date() const timestamp = epoch(dateToday) console.log( timestamp )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM