Bil*_*son 11 .net timezone datetime json json.net
我在使用JSON序列化对象在客户端浏览器上显示正确日期时遇到问题.用户可以定义他们想要查看数据的时区.鉴于此,我将UTC日期转换为服务器上用户的时区.然后我想通过JSON将日期/时间(已经转换为定义的时区)序列化到浏览器.
看起来很简单,但是我一直在使用的JSON序列化程序已经严重破坏了我的日期.服务器为UTC,客户端位于Central(-6).即使我将DateTime.Kind指定为Unspecified,也会调整日期(-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));
Run Code Online (Sandbox Code Playgroud)
ISO日期似乎有效,但我无法使用它们,因为我有第三方控件需要较旧的Microsoft格式...这会调整我的时区.
这是关于我所处的确切情况的长时间讨论。http: //www.telerik.com/community/forums/aspnet-mvc/grid/grids-and-dates.aspx
最重要的是,如果您使用 Microsoft JSON 日期格式,它将始终将 UTC 日期反映为距 1970 年 1 月 1 日 UTC 的毫秒数(刻度)。我无法将服务器上的时间自动转换为本地时间,并通过 JSON 将其应有的时间发送到 Kendo Grid,因为 Kendo Grid 控件将 JS 中的刻度日期实例化为 UTC。显示此日期时,它会自动将该值转换为浏览器的本地时区。
显示服务器转换后的日期值的唯一方法是通过 JSON 将日期作为字符串发送到客户端。