是否可以格式化数据表的日期列? [英] Is it possible to format a date column of a datatable?

查看:21
本文介绍了是否可以格式化数据表的日期列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有一个数据表 dt 并且它有一列 DateofOrder,

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

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

我想将 DateOfOrder 列中的这些日期格式化为这个

I want to format these dates in DateOfOrder column to this

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

任何建议..

推荐答案

最明智的做法是确保您的 DataTable 已键入,并且此列的类型为 DateTime.然后,当您将值实际打印到屏幕上时,您可以在此时设置格式,而无需处理底层数据.

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

这篇关于是否可以格式化数据表的日期列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆