Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to convert exif date time data to timestamp? [duplicate]

In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.

The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.

How to solve this problem?

Thanks in advance.

like image 203
Manthan Sheth Avatar asked Mar 29 '17 03:03

Manthan Sheth


2 Answers

Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:

/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}

console.log(parseDate('2017:03:09 14:49:21').toString());

It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.

like image 94
RobG Avatar answered Sep 25 '22 16:09

RobG


My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:

var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
like image 38
Femi Avatar answered Sep 22 '22 16:09

Femi