1

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?

0

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

3 Comments

It solved the problem. I thought that Javascript wouldn't complain if you pass a integer or a string... As said I'm totally new to this... Thanx a lot!
@MikO: JavaScript will do a lot of automatic string-to-number conversions, but it just happens that the Date constructor accepts either a string or a number, and so it doesn't trigger the automatic conversion. Instead, it looks at what it has and branches, either parsing a string in a given format, or using the number. If a function only allows numbers, odds are high it'll happily auto-convert the string for you (Math.max(10, "100") returns 100, for instance). Just not the Date constructor. :-)
OK, I clearly understand it now. Thanx very much for the solution and for the extra info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.