5

Is it possible in javascript to convert some date in timestamp ?

i have date in this format 2010-03-09 12:21:00 and i want to convert it into its equivalent time stamp with javascript.

1
  • 3
    Can be you be more clear on your requirement?
    – rahul
    Commented Mar 9, 2010 at 6:27

3 Answers 3

18

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.

2
  • You're right, looks like IE only understand Month as string not number, +1
    – YOU
    Commented Mar 9, 2010 at 7:33
  • i think we need to add d[2]+1 also and also need to paresInt for each mathematical operation Commented Mar 9, 2010 at 9:28
9
+(new Date())

Does the job.

1
  • 1
    Wow thanks, that made my day ! No known compatibility issues ? Commented Jun 4, 2013 at 21:41
4

The getTime() method of Date object instances returns the number of milliseconds since the epoch; that's a pretty good timestamp.

2
  • it will return timestamp for today. But i need to get timestamp for some random date Commented Mar 9, 2010 at 6:53
  • 4
    @AshishRajan, that's not true. getTime is an instance method of the Date object. That is, it works on the object itself, not the class. You can call it on any Date you've created: new Date("12/21/2012").getTime() does not equal new Date().getTime() ====== I get that this is an old post, but it should help people hitting this page in the future Commented Nov 12, 2012 at 15:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.