Proper way to format dates from database using javascript / jquery

I call my database which contains datetime data type. The date is as follows:

2005-05-23 16: 06: 00.000

I would like to display this in the table when the user selects a specific item from the list. I invoke my controller action and return all-time Json and put them in a table. The problem is that the date is completely incorrect. The following is displayed:

/ Date (1255470180000) /

The date that is returned is not even legible (which I don’t want to do anyway), so I can’t even get the data if I want. Any ideas?

0
source share
3 answers

I ended up formatting the code in a controller action.

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

Thanks for the help though guys.

+1
source

The date you return is serialized with a marker and a few milliseconds since midnight January 1, 1970 (in UTC). If you isolate the numeric part, convert it to a number and feed it to the Date constructor, you will get the actual date for the work, which you can format as you wish.

 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); 

Alternatively, if the JSON serializer on the server supports the "replacer" parameter, as Crockford and ECMAScript 5th edition do, you can provide a replacement by formatting the date on the string server side and processing it there because you said you did not want to parse the date on the client side (although the jQuery tag suggested to me, maybe so).

+2
source

Another alternative is to return a formatted string from the controller action. You can even leave the timestamp and return the 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), ...} 
0
source

All Articles