计算多行的平均日期差异

时间:2018-03-13 14:03:23

标签: c# winforms nodatime

我需要计算dataGridView中所有行的日期差异的平均值。

我实现了NodaTime(比计算日期差异的传统方法要容易得多),我这样做是为了尝试:

var date1 = new LocalDate(2013, 1, 29);
var date2 = new LocalDate(2018, 1, 23);
Period period = Period.Between(date1, date2.PlusDays(1));
label1.Text = string.Format("{0} anos, {1} meses e {2} dias", period.Years, 
period.Months, period.Days);

现在,我要做的是获取dataGridView的两个日期,在每一行计算日期差异并计算平均值?我希望它能在几年,几个月和几天内展示出来。感谢。

2 个答案:

答案 0 :(得分:3)

不幸的是,没有Period平均值的真实概念,因为它们甚至不能直接比较。例如,“1个月”比“29天”更长还是更短?这取决于月份。移动到平均水平,两个时期“1个月”和“29天”是什么?作为这个问题的有用答案,没有什么是非常明显的,IMO。

天。 具有逻辑意义,并且比年/月/天的平均值更容易定义。

答案 1 :(得分:0)

我必须解决其中一个项目的类似问题。我已经敲了下面似乎有效的代码片段。

假设您在表单上有一个网格用于此测试。

将日期添加到网格列。我在2个日期使用第0列和第1列。

private void Form1_Load(object sender, EventArgs e)
{
        dgGridView.Rows.Add(new DataGridViewRow());
        dgGridView.Rows.Add(new DataGridViewRow());
        dgGridView.Rows.Add(new DataGridViewRow());

        dgGridView.Rows[0].Cells[0].Value = "Feb 01 2018 00:00:00";
        dgGridView.Rows[0].Cells[1].Value = "Feb 03 2018 06:00:45";
        dgGridView.Rows[1].Cells[0].Value = "Feb 02 2018 17:00:00";
        dgGridView.Rows[1].Cells[1].Value = "Feb 03 2018 21:54:21";
        dgGridView.Rows[2].Cells[0].Value = "Feb 04 2017 10:00:00";
        dgGridView.Rows[2].Cells[1].Value = "Feb 07 2018 08:23:26";
}

点击按钮或您选择的任何机制,计算平均值。这是通过计算每个日期范围之间经过的秒数然后除以行数来完成的。

var totalSeconds = 0.0;

 foreach (DataGridViewRow row in dgGridView.Rows)
 {
    var date1 = Convert.ToDateTime(row.Cells[0].Value);
    var date2 = Convert.ToDateTime(row.Cells[1].Value);
    var diff = (date2 - date1).TotalSeconds;

    row.Cells[2].Value = diff;
    totalSeconds += diff;
}

var totalRows = 3;
var aveSeconds = totalSeconds / totalRows;

TimeSpan aveTime = TimeSpan.FromSeconds(aveSeconds);

var totDays = aveTime.Days;
var totHours = aveTime.Hours;
var totMins = aveTime.Minutes;
var totSeconds = aveTime.Seconds;

var ave = $"Days:{totDays} Hours:{totHours} Mins:{totMins} Seconds:{totSeconds}";

然后,您可以从这些总秒数中获取TimeSpan对象,并提取平均值的天数,小时数,分钟数和秒数。

我认为这很有效。如果一个鹰眼的人发现了一个缺陷,请提前道歉,但我希望它可以帮助你。

由于

相关问题