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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:14:05  来源:igfitidea点击:

formatting datetime column in a DataSet

c#asp.netdatasetasp.net-2.0

提问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

You can customize the output using a patternif it is a DateTime object to the format you wanted, "2\2\2009".

您可以使用模式自定义输出,如果它是您想要的格式的 DateTime 对象,“2\2\2009”。

string output1 = dt.ToString(@"mm\dd\yyyy");
string output2 = dt.ToString("mm/dd/yyyy"); //did you mean this?

回答by John Saunders

A DateTimevalue 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 DataFormatStringproperty of the BoundColumnto "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") };