转换date到时间戳在JavaScript?

我想将date转换为时间戳,我的input是26-02-2012 。 我用了

 new Date(myDate).getTime(); 

它说NaN ..任何人都可以告诉如何转换这个?

 var myDate="26-02-2012"; myDate=myDate.split("-"); var newDate=myDate[1]+","+myDate[0]+","+myDate[2]; alert(new Date(newDate).getTime());​ //will alert 1330192800000 

更新:

 var myDate="26-02-2012"; myDate=myDate.split("-"); var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2]; alert(new Date(newDate).getTime()); //will alert 1330210800000 

DEMO (在Chrome,FF,Opera,IE和Safari中testing)。

 var dtstr = "26-02-2012"; new Date(dtstr.split("-").reverse().join("-")).getTime(); 

试试这个函数,它使用Date.parse()方法,不需要任何自定义逻辑:

 function toTimestamp(strDate){ var datum = Date.parse(strDate); return datum/1000; } alert(toTimestamp('02/13/2009 23:31:30')); 
 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()))); } 

您的string不是Date对象指定处理的格式。 你必须自己parsing它,使用像MomentJS这样的dateparsing库,或者使用dateparsing库(比如我可以告诉的DateJS) ,或者按照正确的格式(比如2012-02-29 )之前要求Dateparsing它。

为什么你得到NaN :当你要求new Date(...)处理一个无效的string时,它返回一个Date对象,它被设置为一个无效的date( new Date("29-02-2012").toString()返回"Invalid date" )。 在此状态下调用date对象的getTime()将返回NaN

你只需要扭转你的date数字,然后改变:

  new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11) 

在你的情况下:

  var myDate="26-02-2012"; myDate=myDate.split("-"); new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime(); 

PS英国语言环境在这里并不重要。

 /** * Date to timestamp * @param string template * @param string date * @return string * @example datetotime("dmY", "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()); } 

这个重构的代码将做到这一点

 let toTimestamp = strDate => Date.parse(strDate) 

这适用于所有现代浏览器,除了ie8-