2

Let's say that I receiving a date from api in format: 20191116T202021.000Z

But unfortunately I'am not able to parse this data in javascript:

  var dateToParse = "20191116T202021.000Z"
  var dateFormat = "YYYYMMDD'T'HHmmss.sss'Z'"

  var test = Date.parse(dateToParse, dateFormat)
  console.log(test)

What I want to achieve is to subtract current date with this dateToParse date and see difference in seconds, minutes and days.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
moviss
  • 179
  • 1
  • 2
  • 12
  • 3
    Where did you get the info from that `Date.parse` takes a second argument? – trincot Nov 17 '19 at 11:03
  • It seems you're asking two questions in one: how to parse a string to a date and how to get the difference between two dates in days, minutes, etc. – RobG Nov 17 '19 at 13:03

1 Answers1

3

There is no second argument support for Date.parse. Instead convert your input string to the ISO format by inserting the missing delimiters:

var dateToParse = "20191116T202021.000Z";

var test = Date.parse(dateToParse.replace(/(....)(..)(..T..)(..)/, "$1-$2-$3:$4:")); 
console.log(test); // output as milliseconds
console.log(new Date(test).toJSON()); // output also in JSON format

As noted below, the above regular expression already does the work of parsing the string into its date parts, so you might as well pass those parts to Date.UTC without building another string that needs parsing again. It just needs a little adjustment for the month number:

var dateToParse = "20191116T202021.000Z";

var parts = dateToParse.match(/(....)(..)(..)T(..)(..)(..)\.(...)Z/);
var test = Date.UTC(parts[1], parts[2]-1, parts[3], parts[4], parts[5], parts[6], parts[7]); 
console.log(test); // output as milliseconds
console.log(new Date(test).toJSON()); // output also in JSON format

For more efficiency you would just slice the string into its fixed size pieces without the fancy regular expression:

var dateToParse = "20191116T202021.000Z";

var test = Date.UTC(dateToParse.slice(0,4), 
                    dateToParse.slice(4,6)-1,
                    dateToParse.slice(6,8),
                    dateToParse.slice(9,11), 
                    dateToParse.slice(11,13),
                    dateToParse.slice(13,15),
                    dateToParse.slice(16,19));

console.log(test); // output as milliseconds
console.log(new Date(test).toJSON()); // output also in JSON format
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Great trick with this parsing. Thanks! – moviss Nov 17 '19 at 11:17
  • Agreed, @RobG. Passing the parts directly to `Date.UTC` is more efficient. Not forgetting of course that the month number needs adjusting in that process. Added it to the answer. – trincot Nov 17 '19 at 13:32