date to timestamp in javascript

前端 未结 3 2046
忘了有多久
忘了有多久 2021-01-01 03:28

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 equiva

相关标签:
3条回答
  • 2021-01-01 03:57

    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.

    0 讨论(0)
  • 2021-01-01 04:14
    +(new Date())
    

    Does the job.

    0 讨论(0)
  • 2021-01-01 04:21

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

    0 讨论(0)
提交回复
热议问题