Proper way to format date from database using javascript/jquery

雨燕双飞 提交于 2019-12-01 12:17:36

问题


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:


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




回答2:


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.




回答3:


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), ...}


来源:https://stackoverflow.com/questions/2649057/proper-way-to-format-date-from-database-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!