将日期和时间转换为 Unix 时间戳 [英] Converting Date and Time To Unix Timestamp

查看:47
本文介绍了将日期和时间转换为 Unix 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样显示日期和时间

I'm displaying the date and time like this

2009 年 11 月 24 日 17:57:35

24-Nov-2009 17:57:35

我想将其转换为 unix 时间戳,以便我可以轻松操作它.我需要使用正则表达式来匹配字符串的每个部分,然后从中计算出 unix 时间戳.

I'd like to convert it to a unix timestamp so I can manipulate it easily. I'd need to use regex to match each part of the string then work out the unix timestamp from that.

我对正则表达式很糟糕,但我想出了这个.请提出改进​​意见^.^

I'm awful with regex but I came up with this. Please suggest improvements ^.^

/((d){2}+)-((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)+)-((d){4}+) ((d){2}+):((d){2}+):((d){2}+)/gi

我该怎么做?

推荐答案

如果你只需要一个好的日期解析功能,我会看看 date.js.它将接受您可以抛出的几乎任何日期字符串,并返回一个 JavaScript 日期对象.

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

一旦你有了一个 Date 对象,你就可以调用它的 getTime() 方法,它会给你自 1970 年 1 月 1 日以来的毫秒数.只需将该结果除以 1000 即可获得 unix 时间戳值.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

在代码中,只包含 date.js,然后:

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

这篇关于将日期和时间转换为 Unix 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆