How to convert date to timestamp?

I want to convert date to timestamp, my input is 26-02-2012. I used

new Date(myDate).getTime();

It says NaN.. Can any one tell how to convert this?


Split the string into its parts and provide them directly to the Date constructor:

Update:

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

Try this function, it uses the Date.parse() method and doesn't require any custom logic:

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));

this refactored code will do it

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

this works on all modern browsers except ie8-


There are two problems here. First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.

Second, you need to pass it a string in a proper format.

Working example:

(new Date("2012-02-26")).getTime();

In case you came here looking for current timestamp

var date      = new Date();
var timestamp = date.getTime();

or simply

new Date().getTime();
//console.log(new Date().getTime());