如何更改数据表中日期列的日期格式?

How to change date format for the date column in datatable?

我正在从数据库中填充数据表。 它包含两个字段:DATETIME

两个字段都是datetime

我想遍历数据表并更改 DATE 列的日期格式,即 dd/MM/yyyy

int i = 0;
string d="";
foreach (DataRow dr in dataTable.Rows)
{
    d = dr["DATE"].ToString();
    DateTime date = Convert.ToDateTime(d);
    d = date.ToString("dd/MM/yyyy");
    dataTable.Rows[i]["DATE"] = d;
    i++;
}

我收到以下错误

String was not recognized as a valid DateTime.

无法在 DATE 列中存储 <15/02/2015>。预期类型是 DateTime。我怎样才能实现它?

好吧,你没有告诉我们你是如何创造你的dataTable的,但这是我的想法..

如果您的 DATETIME 列都是 DateTime,那么您需要为它们提供 Datetime 值。不是 string.

在 .NET Framework 中,DateTime 结构没有 any 隐式格式。它只有日期和时间值。当您 尝试 格式化它时,您会得到它的字符串表示形式。这就是为什么 15/02/2015 在您的情况下将是 string,而不是 DateTime

您在 Convert.ToDateTime 方法上得到 FormatException 可能是因为您的 d 值不是 standard date and time format for your CurrentCulture. You can use custom date and time parsing with using DateTime.ParseExact or DateTime.TryParseExact 方法。

string s = "15/02/2015";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None,
                          out dt))
{
    Console.WriteLine(dt);
}

即使您这样做了,为什么要将 string 值保留在 datetime 类型的列中?这完全没有意义 。即使你这样做了,因为 .Rows returns a DataRowCollection,你可能会得到 Collection was modified;枚举操作可能无法执行 错误,因为您在迭代时尝试修改集合。

我建议您为您的字符串值创建另一个 DataTable,并将它们添加到您的 DateTime 值字符串表示形式中,格式如 dd/MM/yyyy

int i = 0;
string d = "";
var stringDataTable = new DataTable();
stringDataTable.Columns.Add("DATE", typeof(String));
stringDataTable.Columns.Add("TIME", typeof(String));

foreach(DataRow dr in dataTable.Rows)
{
   d = ((DateTime)dr["DATE"]).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
   stringDataTable.Rows[i]["DATE"] = d;
   i++;
}