Chinmay235
Chinmay235

Reputation: 3414

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

Upvotes: 3

Views: 3152

Answers (5)

RobG
RobG

Reputation: 147513

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.

Upvotes: 5

Gomzy
Gomzy

Reputation: 431

this will work

    var start_date = "Jan 26,2011 13:51:50 ";
    var d = Date.parse(start_date)/1000;
    console.log(d);

because

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognised or contains illegal date values (e.g. 2015-02-31).

The parse() method takes a date string (such as "Dec 25, 1995") and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Upvotes: 0

Narayansingh Rajput
Narayansingh Rajput

Reputation: 323

Try this its work for all browser

start_date="2011-01-26 13:51:50".replace(" ","T");
start_date = new Date(start_date);
var d = start_date.getTime() / 1000;

Upvotes: 0

Developer
Developer

Reputation: 2706

Try this. I am not sure this result is perfect or not.

var start_date = Date("2011-01-26 13:51:50");
var d = Date.parse(start_date) / 1000;
console.log(d);
//1454478429

Upvotes: 0

abhay vyas
abhay vyas

Reputation: 146

var start_date = "2011-01-26 13:51:50";
var d = Date.now(start_date);
console.log(d);

it will run in mozila you need not to perform any calculation it automatically converts into milliseconds.

Upvotes: 0

Related Questions