在datagridview中计算加载数据期间两个日期的持续时间

时间:2017-12-06 13:22:16

标签: c# datagridview

我有两列包含开始日期和结束日期。我想计算这两者之间的差异。

我的网格完成加载后我可以这样做但是当我将数据加载到网格时是否有机会这样做?

我的加载代码中的短代码片段

DataTable dt = new DataTable();
dt.Columns.Add("StartTime", typeof(DateTime));
dt.Columns.Add("EndTime", typeof(DateTime));
dt.Columns.Add("Duration", typeof(string));

foreach (string File in Files) {
    XDocument doc = XDocument.Load(MyXMLLocation + "\\" + File);
    XElement root = doc.Root;
    root.Descendants();

    string rootName = root.Name.LocalName;
    string logBookName = (string)root.Element("LogbookName");

    foreach (XElement timeSlot in root.Descendants("TimeSlot")) {
        DataRow newRow = dt.Rows.Add();

        newRow["StartTime"] = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "StartTime").FirstOrDefault();
        newRow["EndTime"] = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "EndTime").FirstOrDefault();
        newRow["Duration"] = "something";

2 个答案:

答案 0 :(得分:0)

这会给你时间差异

    newRow["Duration"] = newRow["StartTime"].Subtract(newRow["EndTime"]).TotalMinutes;

答案 1 :(得分:0)

DateTime start = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "StartTime").FirstOrDefault();
DateTime end = (DateTime)timeSlot.Elements().Where(x => x.Name.LocalName == "EndTime").FirstOrDefault();
newRow["StartTime"] = start.ToString();
newRow["EndTime"] = end.ToString();
newRow["Duration"] = (end-start).ToString();