当本地计算机和服务器在不同时区时,Json返回不同的日期 [英] Json returns different dates when local machine and server in different timezones

查看:267
本文介绍了当本地计算机和服务器在不同时区时,Json返回不同的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在json日期解析中遇到一个奇怪的问题.我正在使用以下内容来解析json日期:

I have a strange problem in json date parsing. I am using the following to parse the json date:

dateFormat(new Date(parseInt(user.RegDate.substr(6))), "mm/dd/yyyy")

当我的本地计算机(客户端)与服务器时区位于不同时区时,当我尝试检索用户的注册日期时,它将返回不同的日期.

When my local machine (Client) is in different timezone from the server timezone, then it returns different dates when i try to retrieve the registered date of the users.

例如:

在SQL中的注册日期:2010-07-22 19:00:00.000

Registered date in SQL: 2010-07-22 19:00:00.000

当我在IST时区中的本地计算机中调试时,从JsonResult返回的日期为:

When i debug in local machine which is in IST Timezone, the dates from JsonResult returned are:

/Date(1279805400000)/
Thu Jul 22 19:00:00 UTC+0530 2010

当我从处于EST时区的已部署服务器访问数据时,返回的日期是JsonResult中的相同数据:

The same data when i access it from the deployed server which is in EST timezone, the dates from JsonResult returned are:

/Date(1279843200000)/
Fri Jul 23 05:30:00 UTC+0530 2010

当我将本地计算机更改为EST时区时,此方法非常有效(返回同一日期-7月22日星期四).我在这里想念什么吗?请建议

This works perfect (returns same date - Thu Jul 22) when i change my local machine to EST Timezone. Am i missing anything here?. Please suggest

服务器代码为:

public JsonResult GetregisteredUsersJSON()
{
   var usersList = this.GetregisteredUsers()
   return Json(usersList, JsonRequestBehavior.AllowGet);
}

private List<Users> GetregisteredUsers()
{
    return (from u in _context.mu_Users
        orderby u.Reg_Date descending
        select new Users
        {
            FirstName = u.First_Name,
            LastName = u.Last_Name,
            RegDate = u.Reg_Date
        }).ToList();
}

推荐答案

如果在不指定数据为UTC的情况下将其保存在数据库中,则将希望避免JsonResult在序列化期间不转换DateTime.为此,您将要使用ActionResult而不是JsonResult,然后使用设置为Unspecified的JsonSerializerSettings序列化您的Json数据.

If you save the data in the database without specifying that it is UTC, then you will want to keep JsonResult from converting the DateTime during serialization. To do this you will want to use ActionResult instead of JsonResult, then serialize your Json data with the JsonSerializerSettings set to Unspecified.

public ActionResult GetregisteredUsersJSON() { var usersList = this.GetregisteredUsers() return Content(JsonConvert.SerializeObject(usersList, new JsonSerializerSettings{DateTimeZoneHandling = DateTimeZoneHandling.Unspecified })); }

public ActionResult GetregisteredUsersJSON() { var usersList = this.GetregisteredUsers() return Content(JsonConvert.SerializeObject(usersList, new JsonSerializerSettings{DateTimeZoneHandling = DateTimeZoneHandling.Unspecified })); }

这篇关于当本地计算机和服务器在不同时区时,Json返回不同的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆