日期在javascript中的时间戳 [英] date to timestamp in javascript
问题描述
是否可以在javascript中将时间戳转换为某个日期?
Is it possible in javascript to convert some date in timestamp ?
我的日期格式为 2010-03-09 12:21:00
,我想用javascript将其转换为等效的时间戳.
i have date in this format 2010-03-09 12:21:00
and i want to convert it into its equivalent time stamp with javascript.
推荐答案
响应您的
您需要解析 date字符串以构建 Date
对象,然后可以获得时间戳,例如:
You need to parse the date string to build a Date
object, and then you can get the timestamp, for example:
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}
getTimestamp("2010-03-09 12:21:00"); // 1268158860000
在上面的函数中,我使用一个简单的正则表达式提取数字,然后使用日期构造器,其中包含这部分内容(注意: Date对象将月份处理为基于0的数字,例如0-Jan,1-Feb,...,12月11日).
In the above function I use a simple regular expression to extract the digits, then I build a new Date object using the Date constructor with that parts (Note: The Date object handles months as 0 based numbers, e.g. 0-Jan, 1-Feb, ..., 11-Dec).
然后,我使用一元加运算符获取时间戳.
Then I use the unary plus operator to get the timestamp.
还要注意,时间戳以毫秒为单位.
Note also that the timestamp is expressed in milliseconds.
这篇关于日期在javascript中的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!