[英]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我有 MM/DD/YYYY HH:MM AM/PM 格式的日期示例 07/27/2022 10:36 AM 我想将其转换为 Epoch 时间戳,即 1658898360
The Date
object in Javascript is notoriously tricky to work with, and date parsing is sadly lacking. Javascript 中的
Date
object 是出了名的难以使用,而且遗憾的是缺少日期解析。 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 :一种选择是使用
date-fns
库:
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:您可以使用
date.getTime
方法将其转换为纪元:
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).只需确保您(或客户)处于您期望的同一时区(在这种情况下为 IST)。
Or just add GMT+5:30 to ensure this.或者只是添加 GMT+5:30 来确保这一点。
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.