faisal faisal - 2 months ago 19
ASP.NET (C#) Question

How to change date time format in a grid in asp.net mvc

I want to change my date time format from

7/20/2016 10:30:00 AM
to
20 July 2016 10:30 AM


Bellow is the image in where i want to change the format

enter image description here

Bellow is my code in controller where i have a events data table and in there columns i have added the event name , occurrence time and recovery time

DataTable events = new DataTable();
events.Columns.Add("Event_Name", typeof(string));
events.Columns.Add("Occurrence_Time", typeof(string));
events.Columns.Add("Recovery_Time", typeof(string));


while (reader_events.Read())
{

events.Rows.Add(Convert.ToString(reader_events["Event_Name"]),
Convert.ToString(reader_events["Occurrence_Time"]).ToString(),
Convert.ToString(reader_events["Recovery_Time"]));


}


After that i have passed these events in view data
ViewData["events"] = events;

Bellow is my razor syntax

if (ViewData["events"] != null)
{
if (ViewData.Values != null && ViewData.Values.Count() > 0)
{
foreach (System.Data.DataRow dr in (ViewData["events"] as System.Data.DataTable).Rows)
{
<tr>
<td style="border:1px solid black; color:green;font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif">
@dr[0]

</td>
<td style="border:1px solid black; color:green;font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif">
@dr[1]
</td>
<td style="border:1px solid black; color:green;font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif">
@dr[2]
</td>
</tr>
}
}
}


Any help would be highly appreciated

Answer

you can use the following

@(string.Format("{0:dd MMMM yyyy hh:mm tt}",dr[1]))

in case dr[1] was string, you need to parse it as datetime then apply formatting like this:

@(string.Format("{0:dd MMMM yyyy hh:mm tt}",DateTime.Parse(dr[1])))

please note that the parse in order to work perfectly you need to have some culture validation

another solution, is to setup the datetime from the controller it self by using typeof(DateTime) instead of typeof(string)

for example:

  1. apply the changes in the data table declaration:

events.Columns.Add("Occurrence_Time", typeof(DateTime));

  1. apply the changes in the retrieving part

Convert.ToDateTime(reader_events["Occurrence_Time"]),

  1. You can use the string.Format from the view side

Hope this will help you