C# 格式化数据集中的日期时间列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1182362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
formatting datetime column in a DataSet
提问by Jebli
I have a dataset that is populated by reading excel file. The dataset stores the data from the excel.
我有一个通过读取 excel 文件填充的数据集。数据集存储来自 excel 的数据。
The date in the dataset in in the format 2\2\2009 12:00:00 AMbut i need the data format converted to 2\2\2009. I want to change the format of all the data in that particular column.
数据集中的日期格式为2\2\2009 12:00:00 AM但我需要将数据格式转换为2\2\2009。我想更改该特定列中所有数据的格式。
采纳答案by MusiGenesis
Here's one way:
这是一种方法:
foreach (DataRow row in yourDataTable)
{
DateTime dt = DateTime.Parse(row["Date"].ToString());
row["Date"] = dt.ToShortDateString();
}
This is assuming that the "Date" column is just a text field rather than already a DateTime field.
这是假设“日期”列只是一个文本字段而不是日期时间字段。
回答by omgtitb
回答by John Saunders
A DateTime
value or column has no format. It's just binary data.
甲DateTime
值或列没有格式。它只是二进制数据。
Where do you want the formatted output to appear? That's where you should apply a format string. For instance, if you wanted it to appear in a column of an ASP.NET DataGrid
, then you would set the DataFormatString
property of the BoundColumn
to "mm/dd/yyyy".
您希望格式化的输出显示在何处?这就是您应该应用格式字符串的地方。例如,如果您希望它出现在 ASP.NET 的列中DataGrid
,那么您可以将 的DataFormatString
属性设置BoundColumn
为“mm/dd/yyyy”。
回答by Ajsatis
Try this. It will work
尝试这个。它会工作
var result = from a in ds.Tables[0].AsEnumerable() select new[] { Convert.ToDateTime(a[0]).ToString("dd/MM/yyyy") };
var result = from a in ds.Tables[0].AsEnumerable() select new[] { Convert.ToDateTime(a[0]).ToString("dd/MM/yyyy") };