Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date.parse return NaN in Mozilla Browser

Mozilla browser I have tried get my time-stamp in JavaScript like strtotime in php

My Code:

//var start_date = data.result[0].start_date;
var start_date = "2011-01-26 13:51:50";
var d = Date.parse(start_date) / 1000;
console.log(d);
// 1296030110

Above code is working fine in chrome. But not working in the Mozilla Browser. I am getting NaN value. Please help me.

After search in google I find one solution to add T between the date and time. so I have added. I am getting the output but the output is not the same in both browser.

var start_date = "2011-01-26T13:51:50";
var d = Date.parse(start_date) / 1000;
console.log(d);
//Mozilla = 1296030110
//Chrome  =  1296044910
like image 978
Chinmay235 Avatar asked Jul 19 '26 02:07

Chinmay235


1 Answers

Do not parse strings with the Date constructor or Date.parse (they do the same thing), it is extremely unreliable, especially for non–standard strings (and some that are). To parse "2011-01-26 13:51:50" as a local time, use a library or a simple function like:

function parseDateTime(s) {
  var b = s.split(/\D/);
  return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5])
}

document.write(parseDateTime("2011-01-26 13:51:50") / 1000);

To include validation an support for missing values adds a bit more code on one more line.

like image 127
RobG Avatar answered Jul 21 '26 16:07

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!