【发布时间】:2013-01-20 18:15:51
【问题描述】:
我在使用 JSON 序列化对象在客户端浏览器上显示正确日期时遇到问题。用户能够定义他们想要查看数据的时区。鉴于此,我将 UTC 日期转换为服务器上用户的时区。然后我想通过 JSON 将日期/时间(已经转换为他们定义的时区)序列化到浏览器。
看起来很简单,但是我一直在使用的 JSON 序列化程序严重影响了我的日期。服务器使用 UTC,客户端使用 Central (-6)。即使我将 DateTime.Kind 指定为未指定,日期也会被调整(-12 小时)。
.NET 不知何故知道客户端浏览器所在的时区和服务器所在的时区,并且它从我的日期/时间中否定 -6,即使我已经根据用户的全局设置调整了时间并设置日期的种类未指定。如何让 JSON 序列化程序不尝试调整我的日期?
List<ErrorGridModel> models = Mapper.Map<ErrorCollection, List<ErrorGridModel>>(errors);
foreach (ErrorGridModel m in models)
{
//convert UTC dates to user local dateTime - split out date vs. time for grouping & splitting columns
DateTime dtLocal = TimeZoneInfo.ConvertTimeFromUtc(m.ErrorDate, this.AppContext.User.TimeZoneInfo);
m.ErrorDate = new DateTime(dtLocal.Year, dtLocal.Month, dtLocal.Day, 0, 0, 0, DateTimeKind.Unspecified);
m.ErrorTime = new DateTime(1900, 1, 1, dtLocal.Hour, dtLocal.Minute, dtLocal.Second, DateTimeKind.Unspecified);
}
IQueryable<ErrorGridModel> dataSource = models.AsQueryable();
return new ContentResult() { Content = JsonConvert.SerializeObject(dataSource.ToDataSourceResult(request), new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }), ContentType = "application/json" };
//return Json(dataSource.ToDataSourceResult(request));
ISO 日期似乎可以使用,但我无法使用它们,因为我有需要旧版 Microsoft 格式的 3rd 方控件...它会调整我的时区。
【问题讨论】:
-
这不是您问题的答案,但如果您想将日期逻辑推送到 javascript - 请查看 moment.js momentjs.com
标签: .net json datetime timezone json.net