views:

101

answers:

3

Hi all,

I am calling my database which contains a datetime datatype. The date looks like this:

2005-05-23 16:06:00.000

I would like to display this in a table when a user selects a certain item from a list. I call my controller action and return Json of all the times and put them in a table. The problem is the date is completely wrong. What is displayed is this:

/Date(1255470180000)/

The date that is returned isn't even parsable (which I don't want to do anyway) so I can't even get the data if I wanted to. Any ideas?

+1  A: 

The date you're getting back is serialized to a marker and a number of milliseconds since midnight 1st Jan 1970 (in UTC). If you isolate the numeric portion, convert it into a number, and feed it into the Date constructor you'll get an actual date to work with, which you can then format as you like.

var ticks, dt;

// Isolate the numeric portion of the value
ticks = /[0-9]+/.exec(json.dateValue)[0];

// Convert to a number
ticks = parseInt(ticks);

// Convert to a date
dt = new Date(ticks);

Alternately, if the JSON serializer on the server supports a "replacer" parameter as Crockford's and ECMAScript 5th edition's do, you could supply a replacer that formatted the date into a string server-side and handle it there, since you said you don't want to parse the date client-side (although the jQuery tag suggested to me maybe you did).

T.J. Crowder
I believe it is the number of milliseconds since 1st January 1970 - the epoch.
Tarski
@Tarski: Thanks, I clarified. (In JavaScript, "tick" is sometimes a synonym for "millisecond" although of course that *isn't* how it's used in, say, C.)
T.J. Crowder
Thanks for the solution. I was hoping there was a way to return a non-UTC value from the controller action.The solution you gave also displays: Fri Jan 21 2005 10:29:00 GMT-0500 (Eastern Standard Time) instead of just Fri Jan 21 2005 10:29:00
Darcy
@Darcy: If you want to handle it server-side, I'd drop the jquery and (unless you're using javascript server-side, which I often do) javascript tags from your question. Re your second comment, I did say "...which you can then format as you like." :-)
T.J. Crowder
A: 

The other alternative is to return the formatted string from the controller action. You could even leave the timestamp and return a second field as "Formatted Timestamp" or something similar.

var listFromDb = ...
return new Json(listFromDb.Select(itemFromDb => new List { new 
     { Date = itemFromDb.Date, FormattedDate = FormatDate(itemFromDb.Date), ...}
Mac
A: 

I ended up formatting the code in the controller action instead.

I just cast the datetime property to a string using .ToString() and got the desired results.

Thanks for the help though guys.

Darcy