4

I'm trying to figure out how to render a DateTime value to short string or in the format of dd/mm/yyyy. I tried DateCreated.Value.ToShortDateString() and DateCreated.ToShortDateString(), but it doesn't seemed defined for a DataTable

My current output looks like 2017-04-23T17:39:20.687

How can I render it like dd/mm/yyyy in a DataTable?

@model IEnumerable<TestApp.Models.Announcement>
@{
    ViewBag.Title = "Announcement List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AnnouncementList</h2>

@Html.ActionLink("New Announcement", "New", "Annoucement", null, new {@class = "btn btn-primary"})


<table id="announcement" class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>Title</th>
            <th>Description</th>
            <th>Date Created</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>
@section scripts
{
    <script>
        $(document).ready(function() {
            var table = $("#announcement").DataTable({
                ajax: {
                    url: "/api/announcements",
                    dataSrc: ""
                },
                columns: [
                    {
                        data: "title",
                        render: function(data, type, announcement) {
                            return announcement.title;
                        }
                    },
                    {
                        data: "description",
                        render: function(data, type, announcement) {
                            return announcement.description;
                        }
                    },
                    {
                        data: "dateCreated",
                        render: function(data, type, announcement) {
                            return announcement.dateCreated;
                        }
                    },
                    {
                        data: "id",
                        render: function(data) {
                            return "<button class='btn-link js-delete' data-announcement-id=" +
                                data +
                                ">Delete</button>";
                        }
                    }
                ]
            });


            $("#announcement").on("click",
                ".js-delete",
                function() {
                    var button = $(this);

                    bootbox.confirm("Are you sure you want to delete this annoucement?",
                        function(result) {
                            if (result) {
                                $.ajax({
                                    url: "/api/announcement/" + button.attr("data-annoucement-id"),
                                    method: "DELETE",
                                    success: function() {
                                        table.row(button.parents("tr")).remove().draw();
                                    }
                                });
                            }
                        });
                });
        });
    </script>


}

Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace TestApp.Models
{
    public class Announcement
    {
        public int Id { get; set; }

        [DataType(DataType.MultilineText)]
        public string Title { get; set; }


[DataType(DataType.MultilineText)]
        public string Description { get; set; }

        public DateTime DateCreated { get; set; }
     //   public bool? SendEmail { get; set; }

    }
}

CodingYoshi's posted answer

 <script>
        $(document).ready(function() {
            var table = $("#announcement").DataTable({
                ajax: {
                    url: "/api/announcements",
                    dataSrc: ""
                },
                columns: [
                    {
                        data: "title",
                        render: function(data, type, announcement) {
                            return announcement.title;
                        }
                    },
                    {
                        data: "description",
                        render: function(data, type, announcement) {
                            return announcement.description;
                        }
                    },
                    {
            data: "dateCreated", //also tried putting data: dateCreatedFormatted here too:
                        render: function (data, type, announcement) {
                            return announcement.dateCreatedFormatted;
                        }
                    },
                    {
                        data: "id",
                        render: function(data) {
                            return "<button class='btn-link js-delete' data-announcement-id=" +
                                data +
                                ">Delete</button>";
                        }
                    }
                ]
            });


            $("#announcement").on("click",
                ".js-delete",
                function() {
                    var button = $(this);

                    bootbox.confirm("Are you sure you want to delete this annoucement?",
                        function(result) {
                            if (result) {
                                $.ajax({
                                    url: "/api/announcement/" + button.attr("data-annoucement-id"),
                                    method: "DELETE",
                                    success: function() {
                                        table.row(button.parents("tr")).remove().draw();
                                    }
                                });
                            }
                        });
                });
        });
    </script>

earloc's posted answer

 <script>
        $(document).ready(function() {
            var table = $("#announcement").DataTable({
                ajax: {
                    url: "/api/announcements",
                    dataSrc: ""
                },
                columns: [
                    {
                        data: "title",
                        render: function(data, type, announcement) {
                            return announcement.title;
                        }
                    },
                    {
                        data: "description",
                        render: function(data, type, announcement) {
                            return announcement.description;
                        }
                    },
                    {
                        data: "dateCreated",
                        render: function (data, type, announcement) {
                            return announcement.FormattedDate;
                        }
                    },
                    {
                        data: "id",
                        render: function(data) {
                            return "<button class='btn-link js-delete' data-announcement-id=" +
                                data +
                                ">Delete</button>";
                        }
                    }
                ]
            });


            $("#announcement").on("click",
                ".js-delete",
                function() {
                    var button = $(this);

                    bootbox.confirm("Are you sure you want to delete this annoucement?",
                        function(result) {
                            if (result) {
                                $.ajax({
                                    url: "/api/announcement/" + button.attr("data-annoucement-id"),
                                    method: "DELETE",
                                    success: function() {
                                        table.row(button.parents("tr")).remove().draw();
                                    }
                                });
                            }
                        });
                });
        });
    </script>

and I put this

 public string FormattedDate => DateCreated.ToShortDateString();


 public DateTime DateCreated { get; set; }

in model

1
  • You could format the date in the client-side code that renders the DataTable Commented Apr 23, 2017 at 22:15

3 Answers 3

3

I think you´re mixing technologies here!

Either, provide a formatted string-representation in your Model like (C# 6 Syntax):

public string FormattedDate => DateCreated.ToShortDateString()

and pull this property in JavaScript via:

columns: [
                {
                    data: "dateCreated",
                    render: function(data, type, announcement) {
                        return announcement.FormattedDate;
                    }
                },

or, as Maria suggested, format the date directly on the client-side using techniques like explained here or with help of e.g.: moment.js

(Tha Client-Side JavaScript does not know anything about "ToShortDateString"-Method on a date...)

Sign up to request clarification or add additional context in comments.

2 Comments

For this I'm getting the error: DataTables warning: table id=announcement - Requested unknown parameter 'dateCreated' for row 0, column 2. For more information about this error, please see datatables.net/tn/4 See code above for reference.
As both answers Are kind of correct, i would appreciate an upvote 😀.
3

Add this property to your model:

public string DateCreatedFormatted { get { return this.DateCreated.ToString("dd/MM/yyyy"); } }

Then bind to this property in your JavaScript code.

5 Comments

It should be "dd/MM/yyyy". Lowercase mm means minutes, not months.
I tried this and put it in to the table, but got the following error. See added code above for reference DataTables warning: table id=announcement - Requested unknown parameter 'dateCreatedFormatted' for row 0, column 2. For more information about this error, please see datatables.net/tn/4
@andy javascript is case sensitive so you must use DateCreatedFormatted
I wrote it in camel case because I added code that formats everything in camelcase and thought that's how I would need to add it in webapiconfig.cs var settings = config.Formatters.JsonFormatter.SerializerSettings; settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); settings.Formatting = Formatting.Indented;
I figured out the issue. I was using Dto model and didn't put the formatted public string line in there so it didn't see it. Thanks for the help
0

I know that this post it is a old. I am show my solution working on asp.net Core 3.1 environment. My objective was to display a datetime value obtained from a database column with a datetime2(2) datatype, in a more clear format like dd-mm-yy HH:mm.

Required scripts:

 <script src="~/js/datagrid/datatables/datatables.bundle.js"></script>
 <script src="~/js/dependency/moment/moment.js"></script>

Solution shortcut:

   columns: [
            { title: "Username", data: "username" },
            {
                title: "Registration Date",
                data: "enrollmentTimeStamp",
                render: function (data, type, full, meta) {
                    return moment(data).format('DD-MM-YYYY HH:mm');
                }
            },
        ],

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.