ASP.NET MVC JsonResult Date Format

前端 未结 25 3263
渐次进展
渐次进展 2020-11-21 11:22

I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:

return new JsonRes         


        
25条回答
  •  天涯浪人
    2020-11-21 11:54

    I have been working on a solution to this issue as none of the above answers really helped me. I am working with the jquery week calendar and needed my dates to have time zone information on the server and locally on the page. After quite a bit of digging around, I figured out a solution that may help others.

    I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

    First, I am using a library written by Steven Levithan that helps with dealing with dates on the client side, Steven Levithan's date library. The isoUtcDateTime format is perfect for what I needed. In my jquery AJAX call I use the format function provided with the library with the isoUtcDateTime format and when the ajax call hits my action method, the datetime Kind is set to local and reflects the server time.

    When I send dates to my page via AJAX, I send them as text strings by formatting the dates using "ffffd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz". This format is easily converted client side using

    var myDate = new Date(myReceivedDate);
    

    Here is my complete solution minus Steve Levithan's source, which you can download:

    Controller:

    public class HomeController : Controller
    {
        public const string DATE_FORMAT = "ffffd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";
    
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
    
            return View();
        }
    
        public ActionResult About()
        {
            return View();
        }
    
    
        public JsonResult GetData()
        {
            DateTime myDate = DateTime.Now.ToLocalTime();
    
            return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
        }
    
        public JsonResult ReceiveData(DateTime myDate)
        {
            return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
        }
    }
    

    Javascript:

    
    

    I hope this quick example helps out others in the same situation I was in. At this time it seems to work very well with the Microsoft JSON Serialization and keeps my dates correct across timezones.

提交回复
热议问题