使用 javascript/jquery 从数据库格式化日期的正确方法
我正在调用包含日期时间数据类型的数据库。日期如下所示:
2005-05-23 16:06:00.000
当用户从列表中选择某个项目时,我想在表格中显示此日期。我调用我的控制器操作并返回所有时间的 Json 并将它们放入表中。问题是日期完全错误。显示的是这样的:
/Date(1255470180000)/
返回的日期甚至无法解析(我无论如何都不想这样做),所以如果我想的话,我什至无法获取数据。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您返回的日期被序列化为一个标记和自 1970 年 1 月 1 日午夜(UTC 时间)以来的毫秒数。如果您隔离数字部分,将其转换为数字,并将其输入到
Date
构造函数中,您将获得要使用的实际日期,然后您可以根据需要对其进行格式化。或者,如果服务器上的 JSON 序列化程序支持“替换器”参数(如 Crockford 和 ECMAScript 第五版那样),您可以提供一个替换器,将日期格式化为服务器端字符串并在那里处理它,因为您说过您不这样做想要解析客户端的日期(尽管 jQuery 标签向我建议也许你这样做了)。
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.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).
另一种选择是从控制器操作返回格式化字符串。您甚至可以保留时间戳并返回第二个字段作为“格式化时间戳”或类似的内容。
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.
我最终在控制器操作中格式化了代码。
我只是使用 .ToString() 将日期时间属性转换为字符串并获得了所需的结果。
谢谢你们的帮助。
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.