Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to format a date column of a datatable?

Consider i have a datatable dt and it has a column DateofOrder,

DateofOrder
07/01/2010
07/05/2010
07/06/2010

I want to format these dates in DateOfOrder column to this

DateofOrder
01/Jul/2010
05/Jul/2010
06/Jul/2010

Any suggestion..

like image 361
ACP Avatar asked Jul 09 '10 04:07

ACP


People also ask

How do you format a date?

In America, the date is formally written in month/day/year form. Thus, “January 1, 2011” is widely considered to be correct. In formal usage, it is not appropriate to omit the year, or to use a purely numerical form of the date.

How do I format a date in HTML table?

php $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ". $newDate. " (MM-DD-YYYY)"; ?>


1 Answers

The smartest thing to do would be to make sure your DataTable is typed, and this column is of type DateTime. Then when you go to actually print the values to the screen, you can set the format at that point without mucking with the underlying data.

If that's not feasible, here's an extension method I use often:

public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
{
    foreach(DataRow row in column.Table.Rows)
    {
        row[column] = conversion(row[column]);
    }
}

You could use in your situation like:

myTable.Columns["DateOfOrder"].Convert(
    val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));

It only works on untyped DataTables (e.g. the column type needs to be object, or possibly string).

like image 190
Rex M Avatar answered Nov 04 '22 04:11

Rex M