locked
Json data gives date format something like /Date(1558463400000)/ RRS feed

  • Question

  • User1052662409 posted

    Hi All,

    I am getting data from JsonResult from my controller and binding that data using jquery ajax method.

            [HttpGet]
            public JsonResult getData()
            {
                var jsonData = new
                {
                    data = db.OT_Band_Master.ToList()
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }

    jax method as below

     $.ajax({
                    type: 'GET',
                    url: '@Url.Action("getData","OTBand")',
                datatype: JSON,
                async: false,
                success: function (data) {
                    alert(data.data);
                    _OT = " <div class=\col - lg - 12 tblscroll\"><table id=\"example\" class=\"table table - striped table - bordered\" style=\"width: 100 %\"><thead><tr><th><input type='checkbox' id='checkBoxAll' class='custom - checkbox'/></th><th>@Resources.Resource.manage_band_type</th><th>@Resources.Resource.manage_band_rate</th><th>@Resources.Resource.manage_project_added</th><th>Action</th></tr></thead><tbody>";
                    $(data.data).each(function (i) {
                        alert(data.data[i].dateadded);
                        _OT += "<tr><td><input type='checkbox' name='ID' value='" + data.data[i].bigid + "' class='custom-checkbox chkCheckBoxId' /></td> ";
                        _OT += "<td>" + data.data[i].vcname + "</td>";
                        _OT += "<td>" + data.data[i].vcrate_phour + "</td>";
                        _OT += "<td>" + data.data[i].dateadded + "</td>";

    All data is cumming no issue,  but data.data[i].dateadded gives date format like /Date(1558463400000)/. I want this in dd/mm/yyyy format.

    How to convert.

    please suggest

    Thursday, May 30, 2019 10:20 AM

Answers

  • User-821857111 posted

    Create the following JS function:

    function formattedDateFromJson(jsonDate)
    {
        var d = new Date(parseInt(jsonDate.substr(6)));
        return ("0" + d.getDate()).slice(-2)+ '/' + ("0" + (d.getMonth() + 1)).slice(-2) + '/' + d.getFullYear();
    }

    Then you can call it in your code:

    _OT += "<td>" + formattedDateFromJson(data.data[i].dateadded) + "</td>";

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 30, 2019 10:47 AM

All replies

  • User475983607 posted

    Serializing Entities like you are doing above is not recommended.  When an entity is serialized so are all the navigation properties which results in an exception or more data than expected depending on the schema design.  I recommend crafting a simple class to hold the return data.  This has many names; ViewModel, POCO, DTO... 

    data = db.OT_Band_Master.ToList()

    Once you craft the new DTO, then simply use attributes to control the serialization.  The syntax is dependent on the serializer you are using.

    https://www.newtonsoft.com/json/help/html/DatesInJSON.htm

    https://stackoverflow.com/questions/18022258/fixing-json-date-serialization-from-net-web-method

    Or try returning a type rather than JsonResults better yet use Web API.

    Thursday, May 30, 2019 10:44 AM
  • User-821857111 posted

    Create the following JS function:

    function formattedDateFromJson(jsonDate)
    {
        var d = new Date(parseInt(jsonDate.substr(6)));
        return ("0" + d.getDate()).slice(-2)+ '/' + ("0" + (d.getMonth() + 1)).slice(-2) + '/' + d.getFullYear();
    }

    Then you can call it in your code:

    _OT += "<td>" + formattedDateFromJson(data.data[i].dateadded) + "</td>";

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 30, 2019 10:47 AM
  • User1052662409 posted

    function formattedDateFromJson(jsonDate)
    {
        var d = new Date(parseInt(jsonDate.substr(6)));
        return ("0" + d.getDate()).slice(-2)+ '/' + ("0" + (d.getMonth() + 1)).slice(-2) + '/' + d.getFullYear();
    }

    Its working. 

    Thanks

    return ("0" + d.getDate()).slice(-2)+ '/' + ("0" + (d.getMonth() + 1)).slice(-2) + '/' + d.getFullYear();

    [Just for knowing] Can we modify this format to other format also? like May-30-2019 OR 30 May 2019.

    Thursday, May 30, 2019 11:49 AM
  • User475983607 posted

    Mikesdotnetting always provides excellent advice.  Keep in mind that Web API is designed to return data while MVC is a UI technology.  Web API will return the ISO formatted date which is usually what you want in your JavaScript application.

        public class DefaultController : ApiController
        {
            public MyDateVm Get()
            {
                MyDateVm vm = new MyDateVm()
                {
                    MyDate = DateTime.Now
                };
                return vm;
            }
    

    Model

        public class MyDateVm
        {
            public DateTime MyDate { get; set; }
        }
    

    Result

    {
        "MyDate": "2019-05-30T08:36:08.4975295-04:00"
    }

    It does not matter if you use Web API or mikesdotnetting approach.  Once you have a JavaScript Date() then you can format it however you like using the Date prototypes.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    You can also create your own prototype.

    Thursday, May 30, 2019 12:45 PM
  • User-821857111 posted

    Can we modify this format to other format also? like May-30-2019 OR 30 May 2019.

    Yes. Just to explain, I have used the methods available on the JS Date object (see mgebhard's link) to get parts of the data and then construct a string from them.

    ("0" + d.getDate()).slice(-2) 
    This piece of code gets the day of the month and prefixes it with a "0". Then the slice method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) is used to get the last two characters of the generated string (pay attention to the negative value passed into the slice method), thereby discarding the leading "0" if the day of the month is a double-digit value. This is concatenated with a "/", and then the month is obtained using the same approach. Finally, the year is added.

    If you want the name of days or months, you need to create your own array of the values, and then use the getDay or getMonth value as the index:

    var shortDaysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var d = new Date();

    console.log(shortDaysOfWeek[d.getDay()]); // should return "Thu" if the current date is used

    Thursday, May 30, 2019 1:40 PM