Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c# - 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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...