Reputation: 18741
I'm totally new to Javascript, and I'm getting trouble creating a Date
from milliseconds
.
I have this code:
function (result) {
alert("Retreived millis = " + result.created);
//Prints "Retrieved millis = 1362927649000"
var date = new Date(result.created);
alert("Created Date = " + date);
//Prints "Created Date = Invalid Date"
var current = new Date();
var currentDate = new Date(current.getTime());
alert("Current Date = " + currentDate);
//Prints "Current Date = Sun Apr 14 2013 12:56:51 GMT+0100"
}
The last alert proves that the creation of Date
is working, but I don't understand why the first Date
is not being created correctly, because the retrieved millis
are correct... and as far as I understand in Javascript there're not datatypes, so it can't fail because the retrieved millis
are a string
or a long
, right?
Upvotes: 1
Views: 93
Reputation: 1073968
I suspect result.created
is a string. Since the Date
constructor accepts strings but expects them to be in a different format than that, it fails. (E.g., new Date("1362927649000")
results in an invalid date, but new Date(1362927649000)
gives us Sun Mar 10 2013 15:00:49 GMT+0000 (GMT)
.)
This should sort it (by converting to a number first, so the constructor knows it's dealing with milliseconds since The Epoch):
var date = new Date(parseInt(result.created, 10));
Upvotes: 2