Deserialize javascript date on asp.net mvc 3 server

I struggled with this problem for a while. I am trying to send an object to a client. After the client updates the object, I would like to send it back to the server and save it in my database. The first part works great. However, when I send it back, all dates are mixed up and start during the year 0001. I assume that since it cannot deserialize the date. Howe can I publish a json object with a date property and deserialize it to a type on a server with asp.net mvc 3?

Group

public class Group
{
    public Group();

    public string CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
    public string Description { get; set; }
    public string Name{ get; set; }
    public string Status { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime UpdatedOn { get; set; }
}

and

    public JsonResult updateGroup(Group group)
    {
        var result = Repository.updateGroup(group);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

and on the client I received

    $.ajax({
        url: '../updateGroup',
        type: 'POST',
        data: JSON.stringify(group),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function(){ success(); }
    });
+3
source share
2 answers

ASP.NET MVC 3 JavaScriptSerializer . :

Date, JSON as "\/ ( ) \/". , (), 01 1970 . UTC.

MaxValue (12/31/9999 11:59:59 PM) MinValue (1/1/0001 12:00:00 AM).

, :

{ CreatedOn: '\/Date(1299098853123)\/', CreatedBy: 'foo', ... }

, :

// taking the local time but this could be any javascript Date object
var now = new Date(); 
var group = {
    CreatedBy: 'foo',
    CreatedOn: '\/Date(' + now.getTime() + ')\/',
    Description: 'some description',
    Name: 'some name',
    etc...
};

a >

, UTC, , - ( UTC):

public ActionResult UpdateGroup(Group group)
{
    DateTime serverCreatedOn = group.CreatedOn.ToLocalTime();
    ...
}

URL- :

url: '../updateGroup'

URL- URL-, :

url: '@Url.Action("updateGroup")'

UPDATE:

:

// taking the local time but this could be any javascript Date object
var now = new Date(); 
var group = {
    CreatedBy: 'foo',
    CreatedOn: now.toUTCString(),
    Description: 'some description',
    Name: 'some name',
    etc...
};
+4

. UTC ,

    var now = new Date();
    group.CreatedOn = now.toLocaleString();

    var now = new Date();
    group.CreatedOn = now;

0

Source: https://habr.com/ru/post/1795851/


All Articles