Search code examples
javascriptdatetime

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?


Solution

  • 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());

    Updated: Also, you can use a regular expression to split the string, for example:

    const dtStr = "26/02/2012";
    const [d, m, y] = dtStr.split(/-|\//); // splits "26-02-2012" or "26/02/2012"
    const date = new Date(y, m - 1, d);
    console.log(date.getTime());