将 Datetimes(HH:MM) 加在一起形成一个 (HHHH:MM)?

Adding Datetimes(HH:MM) together to form a (HHHH:MM)?

我在日期时间计算上苦苦挣扎 - 它总是让我感到困惑!我更喜欢数字而不是时间!

所以我有各种单元格,每个单元格中都有总小时数。该行的末尾是总计 Hours:Minutes 列,它将这些单元格加在一起。每个单元格的值都是一个字符串,因此需要先转换为 DateTime。

我的问题是我到底该怎么做?以下是我目前的一些片段:

string cellvalue = e.Data.GetData(typeof(string)) as string;
Point cursorLocation = this.PointToClient(new Point(e.X, e.Y));

DataGridView.HitTestInfo hittest = dataGridView1.HitTest(cursorLocation.X, cursorLocation.Y);
DateTime calc = DateTime.Parse((dataGridView1[hittest.ColumnIndex + 1, hittest.RowIndex].Value.ToString()));
dataGridView1[dataGridView1.ColumnCount, hittest.RowIndex].Value = ??????

有什么想法吗?

看来您应该改用 TimeSpan,所以您应该使用

TimeSpan calc = TimeSpan.Parse((dataGridView1[hittest.ColumnIndex + 1, hittest.RowIndex].Value.ToString()));

您可以使用 + 添加时间跨度。

要格式化字符串以表示 totalhours:minutes,您可以使用

String.Format("{0}:{1}", Math.Floor(ts.TotalHours), ts.Minutes)

(假设时间跨度为正)。

在您有 "Total hours" 的单元格中,它是字符串、双精度值还是 TimeSpan 值?

在我看来你不需要 DateTime,只需将所有 "TotalHours" 转换为 TimeSpan 并将 TimeSpans 加在一起,你在 Total 单元格中显示的就是你的 TimeSpan TotalHours。

参见 TimeSpan 构造函数、TotalHours 和 Add。