简体   繁体   English

使用javascript / jquery从数据库格式化日期的正确方法

[英]Proper way to format date from database using javascript/jquery

I am calling my database which contains a datetime datatype. 我正在调用包含日期时间数据类型的数据库。 The date looks like this: 日期看起来像这样:

2005-05-23 16:06:00.000 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. 我调用我的控制器动作,并一直返回Json并将它们放在表中。 The problem is the date is completely wrong. 问题是日期是完全错误的。 What is displayed is this: 显示的内容是:

/Date(1255470180000)/ /日期(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? 有任何想法吗?

The date you're getting back is serialized to a marker and a number of milliseconds since midnight 1st Jan 1970 (in UTC). 自1970年1月1日午夜以来(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. 如果隔离数字部分,将其转换为数字,然后将其输入到Date构造函数中,您将获得一个实际的日期,然后可以根据需要格式化它。

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). 或者,如果服务器上的JSON序列化程序支持Crockford和ECMAScript 5th Edition的“ replacer”参数,则可以提供一个将日期格式化为字符串的服务器端并在那里处理的替代器,因为您说不想要解析客户端的日期(尽管jQuery标记建议我也许已经做到了)。

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. 我只是使用.ToString()将datetime属性转换为字符串,并获得了所需的结果。

Thanks for the help though guys. 谢谢你们的帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM