0

I have a string that I retrieve from a JSON object and I am trying to cast that to a javascript date variable as given below but its returning an Invalid date all the time. Any reasons why?

jsonObj["dateValue"]; //has a value: 2016-11-04T08:08:42.5780021+00:00
var dateValue = new Date(jsonObj["dateValue"]); // returns invalid date??

JsFiddle

8
  • 1
    do a typeof of jsonObj["dateValue"], what is that returning? Commented Nov 4, 2016 at 14:05
  • 2
    if you do a new Date("2016-11-04T08:08:42.5780021+00:00") it shall return a valid date object, provided that its a string Commented Nov 4, 2016 at 14:05
  • its returning string when i did typeof. Commented Nov 4, 2016 at 14:06
  • Please create a snippet that reproduces the problem, because the code you posted does not give this error. Commented Nov 4, 2016 at 14:07
  • can you post the exact value of jsonObj["dateValue"] Commented Nov 4, 2016 at 14:07

2 Answers 2

1

You have the jsonObj as an array not an object. The first value in the array is your actual object.

try:

 var dateValue = new Date(jsonObj[0]["dateValue"]);

Or simplify your jsonObj value by making it the object, not a wrapping array.

Updated fiddle - https://jsfiddle.net/wyqzmhz1/

Sign up to request clarification or add additional context in comments.

Comments

0

Your jsonObj is an array - you should thus take the first item

var jsonObj = [{
dateValue : "2016-11-04T08:08:42.5780021+00:00"
}];

var dateValue = new Date(jsonObj[0]["dateValue"]);
console.log(dateValue);

Comments

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.