You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决DataTable中DateTime转时间格式时的无效DateTime字符串错误?

Fixing "String was not recognized as a valid DateTime" When Converting DataTable DateTime to Time Only

Hey there, let's tackle that frustrating error you're hitting when trying to extract just the time from DateTime values in your DataTable. That message almost always means the system can't properly parse the value it's working with into a DateTime object—so let's walk through the most common fixes step by step:

1. First, Check What Type Your DataTable Column Actually Is

Sometimes you assume a column stores DateTime values, but it's actually storing strings (maybe from a database query that didn't map types correctly, or manual data entry). Let's verify first:

// Print the data type of your column to confirm
Console.WriteLine(dataTable.Columns["YourDateTimeColumn"].DataType);

If it's a string type, you need to explicitly parse it using the exact format of your string data. For example, if your strings look like 2024-05-20 14:30:00, use this safe parsing method:

DateTime parsedDate;
var dateString = row["YourDateTimeColumn"].ToString();

// Use TryParseExact to avoid crashes from invalid values
if (DateTime.TryParseExact(dateString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
{
    // Convert to time-only format
    string timeOnly = parsedDate.ToString("HH:mm:ss"); // Use "h:mm tt" for 12-hour AM/PM
    // Use the time string as needed (store back in DataTable, display, etc.)
}
else
{
    // Handle invalid entries—log the bad value or set a default
    Console.WriteLine($"Oops, couldn't parse this date: {dateString}");
}

2. If the Column Is Definitely DateTime Type

If your column is already storing DateTime objects, you might be accidentally converting it to a string first and then re-parsing it (a common unnecessary step that causes errors). Skip the extra parsing and format the DateTime directly:

// Make sure to check for DBNull if the column allows nulls
if (row["YourDateTimeColumn"] != DBNull.Value)
{
    DateTime dateValue = (DateTime)row["YourDateTimeColumn"];
    string timeOnly = dateValue.ToString("HH:mm:ss"); // Adjust format to your needs
    // Use the time string here
}

3. Batch Convert an Entire DataTable Column

If you need to update the entire DataTable to show time-only values, add a new calculated column or overwrite the existing one:

// Add a new column for time-only values
dataTable.Columns.Add("TimeOnly", typeof(string));

foreach (DataRow row in dataTable.Rows)
{
    if (row["YourDateTimeColumn"] != DBNull.Value)
    {
        DateTime dateVal = (DateTime)row["YourDateTimeColumn"];
        row["TimeOnly"] = dateVal.ToString("HH:mm:ss");
    }
    else
    {
        row["TimeOnly"] = DBNull.Value;
    }
}

Key Tips to Avoid This Error Later

  • Always use DateTime.TryParseExact instead of ParseExact: It won't crash your program if it hits an invalid value, and lets you handle bad data gracefully.
  • Match your format string exactly: Double-check that your format (like yyyy-MM-dd vs MM/dd/yyyy) matches how the date is stored in your DataTable.
  • Specify culture if needed: Use CultureInfo.InvariantCulture if your data uses standard formats, or the specific culture that matches your data to avoid region-based parsing issues.

内容的提问来源于stack exchange,提问作者john true

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:04:52