使用DataRowExtension解析TimeSpan

时间:2018-12-12 14:52:52

标签: c# casting timespan

我想使用DataRowExtension将DataRow中的字段值作为TimeSpan(格式如mm:ss),但是它给了我System.InvalidCastException,如下所示

var time = staffItems.Rows[0].Field<TimeSpan>("TIME_DURATION"); // System.InvalidCastException

但是当将此值作为字符串并将其解析为TimeSpan之后,就不会出现问题。

var time = staffItems.Rows[0].Field<string>("TIME_DURATION"); // time : 0:43
var time2 = TimeSpan.Parse(time); // time2 : 00:43:00

问题是,如何使用DataRowExtension进行此操作而无需任何额外的解析或转换。

3 个答案:

答案 0 :(得分:0)

首先,您必须解析然后获取时间部分

var time = TimeSpan.Parse(staffItems.Rows[0]["TIME_DURATION"]);
var time2 = time.ToString(@"mm\:ss");

如果要从datarowextension中获取它。您必须创建数据表并为“ TIME_DURATION”列指定时间对象。您可以通过以下方法做到这一点:

using System;
using System.Data;

class Program
{
    static void Main()
    {
        //
        // Loop over DataTable rows and call the Field extension method.
        //
        foreach (DataRow row in GetTable().Rows)
        {
            // Get first field by column index.
            int weight = row.Field<int>(0);

            // Get second field by column name.
            string name = row.Field<string>("Name");

            // Get third field by column index.
            string code = row.Field<string>(2);

            // Get fourth field by column name.
            DateTime date = row.Field<DateTime>("Date");

            // Display the fields.
            Console.WriteLine("{0} {1} {2} {3}", weight, name, code, date);
        }
    }

    static DataTable GetTable()
    {
        DataTable table = new DataTable(); // Create DataTable
        table.Columns.Add("Weight", typeof(int)); // Add four columns
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Code", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));
        table.Rows.Add(57, "Koko", "A", DateTime.Now); // Add five rows
        table.Rows.Add(130, "Fido", "B", DateTime.Now);
        table.Rows.Add(92, "Alex", "C", DateTime.Now);
        table.Rows.Add(25, "Charles", "D", DateTime.Now);
        table.Rows.Add(7, "Candy", "E", DateTime.Now);
        return table;
    }
}

答案 1 :(得分:0)

以下方法将以string扩展方法将TimeSpan解析为DataRow

public static TimeSpan ExtractTimeData(this DataRow row, string column)
{
    // check column exists in dataTable
    var exists = row.Table.Columns.Contains(column);

    if (exists)
    {
        // ensure we're not trying to parse null value
        if (row[column] != DBNull.Value)
        {
            TimeSpan time;

            if (TimeSpan.TryParse(row[column].ToString(), out time))
            {
                // return if we can parse to TimeSpan
                return time;
            }
        }
    }

    // return default TimeSpan if there is an error
    return default(TimeSpan);
}

您可以像这样使用它:

TimeSpan time = row.ExtractTimeData("TIME_DURATION");
string timeString = time.ToString(@"h\:mm");

答案 2 :(得分:0)

TIME_DURATION字段可能是vharchar或来自DataTable的其他内容。它必须等效于TimeSpan。