crony
crony

Reputation: 511

How do I format datetime column in jQuery Datable(server side)

I am implementing jQuery server-side datatable. I have 1 date column and 2 datetime columns. All 3 are displaying on datatable in a wrong format.

Received Date: /Date(1373947200000)/ (Date)

Created Date: /Date(1374845903000)/ (Datetime)

Updated Date: /Date(1374845903000)/ (Datetime)

How can I display in a correct format?

.cshtml

<table id="disparityForm" class="ui celled table" style="width:100%">
    <thead>
        <tr>
            <th>Status</th>
            <th>Received Date</th>
            <th>Member ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Created User</th>
            <th>Created Date</th>
            <th>Updated User</th>
            <th>Updated Date</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Status</th>
            <th>Received Date</th>
            <th>Member ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Created User</th>
            <th>Created Date</th>
            <th>Updated User</th>
            <th>Updated Date</th>
        </tr>
    </tfoot>
</table>

<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css" rel="stylesheet" />
<link href="~/Content/DataTables/media/css/dataTables.semanticui.min.css" rel="stylesheet" />

@section scripts{
    <script src="~/Scripts/DataTables/media/js/jquery.dataTables.min.js"></script>
    <script src="~/Scripts/DataTables/media/js/dataTables.semanticui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.js"></script>

    <script>
        $(document).ready(function () {
            $("#disparityForm").DataTable({
                "ajax": {
                    "url": "/DisprtyForm/GetList",
                    "type": "POST",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "STS", "name": "STS" },
                    { "data": "RECEIVED_DATE", "name": "RECEIVED_DATE" },
                    { "data": "MBR_AGP_ID_NUM", "name": "MBR_AGP_ID_NUM" },
                    { "data": "MBR_FST_NME", "name": "MBR_FST_NME" },
                    { "data": "MBR_LST_NME", "name": "MBR_LST_NME" },
                    { "data": "CREATE_USR_ID", "name": "CREATE_USR_ID" },
                    { "data": "AUDIT_CREATE_DT", "name": "AUDIT_CREATE_DT" },
                    { "data": "UPDT_USR_ID", "name": "UPDT_USR_ID" },
                    { "data": "AUDIT_UPDT_DT", "name": "AUDIT_UPDT_DT" },
                ],

                "serverSide": "true",
                "order": [0, "asc"],
                "processing": "true",
                "language": {
                    "processing": "processing...Please wait"
                }
            });
        })

    </script>
}

Below is the c# Code that return json format.

 [HttpPost]
    public ActionResult GetList()
    {
        //Server side Parameters
        int start = Convert.ToInt32(Request["start"]);
        int length = Convert.ToInt32(Request["length"]);
        string searchValue = Request["search[value]"];
        string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][Name]"];
        string sortDirection = Request["order[0][dir]"];


        List<DISPRTY_FORM> disprtyFormList = new List<DISPRTY_FORM>();
        using (DBModel db = new DBModel())
        {
            disprtyFormList = db.DISPRTY_FORM.ToList<DISPRTY_FORM>();
            int totalrows = disprtyFormList.Count;

            //Todo filtering

            int totalRowsAfterFiltering = disprtyFormList.Count;

            //sorting
            disprtyFormList = disprtyFormList.OrderBy(sortColumnName + " " + sortDirection).ToList<DISPRTY_FORM>();

            //paging
            disprtyFormList = disprtyFormList.Skip(start).Take(length).ToList<DISPRTY_FORM>();

            var jsonResult = Json(new { data = disprtyFormList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalRowsAfterFiltering }, JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }
    }

Upvotes: 4

Views: 10820

Answers (3)

Moorthysmart M
Moorthysmart M

Reputation: 1

AUDIT_CREATE_DT

{
    "data": "AUDIT_CREATE_DT",
    "render": function (data) {
        var date = new Date(data);
        var month = date.getMonth() + 1;
        return (month.toString().length > 1 ? month : "0" + month) + "/" + date.getDate() + "/" + date.getFullYear();
    }
}

Upvotes: 0

Asif Raza
Asif Raza

Reputation: 1021

You can use third party library "moment.js". Make sure your have added moment.js library

  { data: "AUDIT_CREATE_DT" ,
                          "render": function (value) {
                              if (value === null) return "";
                              return moment(value).format('DD/MM/YYYY');
                          }

I hope this solution will work. Update: here is official link of Moment.js

Upvotes: 7

Shyju
Shyju

Reputation: 218942

/Date(1374845903000)/ 

That is the Epoch representation of the DateTime value you have. The json serializer (used by asp.net mvc) converted the DateTime object value to it's corresponding unix epoch time (the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970).

Now for the datatable, for each column, you can override how it should be rendered in the cell. All you have to do is, execute some javascript code to convert this epoch value to a readable string. So we will write a little helper method to format the timestamp value to a readable string representation and specify that little helper method as the callback for render for those date columns

$(document).ready(function () {

    // Accepts the epoch timestamp value and return a Date string
    function getDateString(date) {
        var dateObj = new Date(parseInt(date.substr(6)));
        return dateObj.toDateString();
    }

    $('#disparityForm').DataTable({
        "ajax": {
            "url": "/Home/GetList",
            "type": "POST",
            "datatype": "json"
        },
        "columns": [
            { "data": "STS", "name": "STS" },
            { "data": "MBR_FST_NME", "name": "MBR_FST_NME" },
            {
                "data": "AUDIT_CREATE_DT", "name": "AUDIT_CREATE_DT", 
                "render": function (data) { return getDateString(data); }
            }
        ]
    });

});

That should fix the created date column. Do the same for other columns as well.

Upvotes: 4

Related Questions