Convert JSON Date to JavaScript Date in ASP.Net

Last Reply 9 months ago By dharmendr

Posted 10 months ago

How to set format for date in Json?

https://ibb.co/kSwJ5z

I have gridview with date field. But the date is showing like this which I attached in link. Eg there may multiple employees , their birthday may change. But date is displaying like this, I have to display like normal date alone.

https://ibb.co/kr3o8K

You are viewing reply posted by: dharmendr 9 months ago.
Posted 9 months ago Modified on 9 months ago

Hi SUJAYS,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" />
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
        <asp:BoundField DataField="DOB" HeaderText="Date Of Birth" />
        <asp:BoundField DataField="DOBJson" HeaderText="Json Date Of Birth" />
    </Columns>
</asp:GridView>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: 'POST',
            url: 'Default.aspx/GetEmployees',
            datatype: "json",
            data: {},
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                var employees = $.parseJSON(data.d);
                var row = $("[id*=gvEmployees] tr:last-child").clone(true);
                $("[id*=gvEmployees] tr").not($("[id*=gvEmployees] tr:first-child")).remove();
                $.each(employees, function (i, item) {
                    var customer = $(this);
                    $("td", row).eq(0).html(item.EmployeeId);
                    $("td", row).eq(1).html(item.FirstName);
                    $("td", row).eq(2).html(item.LastName);
                    $("td", row).eq(3).html(item.Country);
                    $("td", row).eq(4).html(ConvertJsonDateToDateTime(item.DOB));
                    $("td", row).eq(5).html(item.DOB);
                    $("[id*=gvEmployees]").append(row);
                    row = $("[id*=gvEmployees] tr:last-child").clone(true);
                });
            },
            error: function (data) { debugger; alert(data.responseText); }
        });
    });

    function ConvertJsonDateToDateTime(date) {
        var parsedDate = new Date(parseInt(date.substr(6)));
        var newDate = new Date(parsedDate);
        var month = newDate.getMonth() + 1;
        var day = newDate.getDate();
        var year = newDate.getFullYear();
        return day + "/" + month + "/" + year;
    }
</script>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDummyRow();
    }
}

private void BindDummyRow()
{
    System.Data.DataTable dummy = new System.Data.DataTable();
    dummy.Columns.Add("EmployeeID");
    dummy.Columns.Add("FirstName");
    dummy.Columns.Add("LastName");
    dummy.Columns.Add("Country");
    dummy.Columns.Add("DOB");
    dummy.Columns.Add("DOBJson");
    dummy.Rows.Add();
    gvEmployees.DataSource = dummy;
    gvEmployees.DataBind();
}

[System.Web.Services.WebMethod]
public static string GetEmployees()
{
    NorthwindModel.NorthwindEntities entities = new NorthwindModel.NorthwindEntities();
    List<Employee> employees = entities.Employees
        .Select(x => new Employee
        {
            EmployeeId = x.EmployeeID,
            FirstName = x.FirstName,
            LastName = x.LastName,
            Country = x.Country,
            DOB = x.BirthDate
        }).ToList();

    return (new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(employees));
}
public class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Country { get; set; }
    public DateTime? DOB { get; set; }
}

VB.Net

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindDummyRow()
        End If
    End Sub

    Private Sub BindDummyRow()
        Dim dummy As System.Data.DataTable = New System.Data.DataTable()
        dummy.Columns.Add("EmployeeID")
        dummy.Columns.Add("FirstName")
        dummy.Columns.Add("LastName")
        dummy.Columns.Add("Country")
        dummy.Columns.Add("DOB")
        dummy.Columns.Add("DOBJson")
        dummy.Rows.Add()
        gvEmployees.DataSource = dummy
        gvEmployees.DataBind()
    End Sub

    <System.Web.Services.WebMethod>
    Public Shared Function GetEmployees() As String
        Dim entities As NorthwindModel.NorthwindEntities = New NorthwindModel.NorthwindEntities()
        Dim employees As List(Of Employee) = entities.Employees.[Select](Function(x) New Employee With {
            .EmployeeId = x.EmployeeID,
            .FirstName = x.FirstName,
            .LastName = x.LastName,
            .Country = x.Country,
            .DOB = x.BirthDate
        }).ToList()
        Return (New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(employees))
    End Function

    Public Class Employee
        Public Property EmployeeId As Integer
        Public Property FirstName As String
        Public Property LastName As String
        Public Property Country As String
        Public Property DOB As DateTime?
    End Class

Screenshot