user2431170 user2431170 - 2 years ago 145
AngularJS Question

Invalid date - Number to Date

I was trying to convert a Number to Date in Javascript. Below is the code which I have tried

var newDate = new Date(1012256900000);
console.log("Test: ",newDate.toString('MMM-yyyy'));

This is working fine.
But when I get it from $rootScope object, am getting invalid date :(

var newDate = new Date($rootScope.lastLoginTime);
console.log("Test: ",newDate.toString('MMM-yyyy'));

This is printing Invalid Date. FYI,
$rootScope.lastLoginTime = 1463256900000;

Answer Source

Gonna take a guess here, but look at what I did in the browser console:

new Date(1463256900000)
> [date] Sat May 14 2016 21:15:00 GMT+0100

new Date("1463256900000")
> [date] Invalid date

Completely wild guess, but perhaps you should ensure you are passing a number, not a string, to new Date() - the constructor behaves very differently in either case.

Consider instead trying this:

var newDate = new Date();

setTime takes a numeric argument only, and will convert your string to a number for you if you pass it one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download