Search code examples
javascriptdatetimeepoch

How can I create epoch from String?


All, I need to create epoch time from a string using Javascript. Now I know that I can use the following:

var dateStr = '01/01/2016 1:10 PM'
var dateObj = new Date(dateStr);
console.log(dateObj.getSeconds());

The problem I have is that using the above code my data has the millisecond in it. Take the following as an example:

var dateStr = '01/01/2016 1:10:49.181 PM'
var dateObj = new Date(dateStr);
console.log(dateObj.getSeconds());

Using that format, I get a NaN error. Is there a way to convert the date time in the second example to epoch while retaining the milliseconds?


Solution

  • Below is a possible workaround:

    var dateStr = '01/01/2016 1:10:49.181 PM',
        reg = new RegExp(/\.[0-9]{1,3}/);
    
    var dateObj = new Date(dateStr.replace(reg, ''));
    
    console.log(
      (dateObj.getTime() + 1000 * Number(reg.exec(dateStr)[0]))
    );
    

    This will include the milliseconds in the final result (1451650249181). You may also discard them entirely, in which case you only need the replace part without the exec part.

    Reverse operation

    Below is a possible approach for the reverse operation, using the standard Date methods.

    Beware: barely tested.

    var ts = new Date(1451650249181);
    
    var dateStr =
      ('0' + ts.getDate()).substr(-2, 2) + '/' +
      ('0' + (ts.getMonth() + 1)).substr(-2, 2) + '/' +
      ts.getFullYear() + ' ' +
      (ts.getHours() % 12 || 12) + ':' +
      ('0' + ts.getMinutes()).substr(-2, 2) + ':' +
      ('0' + ts.getSeconds()).substr(-2, 2) + '.' +
      ('00' + (ts.getTime() % 1000)).substr(-3, 3) + ' ' +
      (ts.getHours() >= 12 ? 'PM' : 'AM');