1

I have a datetime in SQL server that i return from a controller method in my MVC project using return json()

I get this format in my json-response:

time: "/Date(1409763303817)/"

I try to use this data in a table in my UI with this code:

$("#missingTime").html(new Date(data3.time).toDateString());

I get "Invalid Date" in my column.

What am i doing wrong?

Edit: Found a solution

new Date(parseInt(data3.time.replace("/Date(", "").replace(")/",""), 10)
Lord Vermillion
  • 5,264
  • 20
  • 69
  • 109

2 Answers2

2

The JSON value you have is not a valid number to be parsed into a JavaScript Date object. A quick fix would be to strip out the UTC value (the numbers) from your string using a regular expression and pass this to your function (after parsing into a number), like so:

var regEx = /\d+/g;
var utcInfo = data3.time.match(regEx);
$("#missingTime").html(new Date(parseInt(utcInfo)).toDateString());

Although you might want to check why your JSON response is giving you the incorrect value in the first place. The value in the JSON object needs to be as follows in order for your JS code to work:

time: 1409763303817
SheedySheedySheedy
  • 536
  • 1
  • 6
  • 14
  • What should i change on the serverside? Time is a regular datetime in my object, public System.DateTime time { get; set; }. The object is returned as json with MVCs return json(object). – Lord Vermillion Sep 04 '14 at 15:02
  • Do you mean .Net MVC? – SheedySheedySheedy Sep 04 '14 at 15:04
  • Yes, a regular MVC 4 project – Lord Vermillion Sep 04 '14 at 15:09
  • Then, with the greatest of respect, that is no longer a JavaScript question. I have no knowledge of that framework. What you need to pass to the JavaScript Date function is a number representing the UTC. That is the set of numbers which is represented in the string you have now. How you get that out of the database is another issue entirely. – SheedySheedySheedy Sep 04 '14 at 15:16
  • I have edited my answer to show you what value you need to get back from the database in your JSON object, in order for your present JS code to work. – SheedySheedySheedy Sep 04 '14 at 15:20
  • @TobiasOlofsson I am not sure why you won't accept the answer, because the code I have given you will achieve what you asked for. – SheedySheedySheedy Sep 05 '14 at 14:55
0

If you take use of the MVC-Model the Controller-Layer should convert the time into a format the View can handle.

See, a Time is more than Minutes, Hours and Seconds. Its depends on the Timezone the calling Browser physicaly is.

Grim
  • 1,938
  • 10
  • 56
  • 123