我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
其他回答
/**
* Date to timestamp
* @param string template
* @param string date
* @return string
* @example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
这里有两个问题。 首先,您只能在日期的实例上调用getTime。您需要将new Date括在括号中或将其赋值给变量。
其次,您需要以适当的格式传递一个字符串。
工作的例子:
(new Date("2012-02-26")).getTime();
其他开发人员已经提供了答案,但在我自己的方式中,你可以在不创建任何用户定义函数的情况下执行此操作,如下所示:
var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
为了将(ISO)日期转换为Unix时间戳,我最终得到了一个比所需时间长3个字符的时间戳,所以我的年份大约是50k…
我要除以1000 new Date('2012-02-26').getTime() / 1000
下面的代码将把当前日期转换为时间戳。
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);