In response to your edit:
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
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.
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());
Best Answer
Timestamp in milliseconds
To get the number of milliseconds since Unix epoch, call
Date.now
:Alternatively, use the unary operator
+
to callDate.prototype.valueOf
:Alternatively, call
valueOf
directly:To support IE8 and earlier (see compatibility table), create a shim for
Date.now
:Alternatively, call
getTime
directly:Timestamp in seconds
To get the number of seconds since Unix epoch, i.e. Unix timestamp:
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):
Timestamp in milliseconds (higher resolution)
Use
performance.now
: