1

我试图仅显示 24 小时前或更短时间添加到我的数据库中的数据。但是,由于某种原因,我编写的代码不起作用,并且我的数据库中的两个条目(一个来自 1 小时前,一个来自 2 天前)都出现了。我的方程式有问题吗?谢谢!

public void UpdateValues()
    {
        double TotalCost = 0;
        double TotalEarned = 0;
        double TotalProfit = 0;
        double TotalHST = 0;
        for (int i = 0; i <= Program.TransactionList.Count - 1; i++)
        {
            DateTime Today = DateTime.Now;
            DateTime Jan2013 = DateTime.Parse("01-01-2013"); //Hours since Jan12013
            int TodayHoursSince2013 = Convert.ToInt32(Math.Round(Today.Subtract(Jan2013).TotalHours)); //7
            int ItemHoursSince2013 = Program.TransactionList[i].HoursSince2013; //Equals 7176, and 7130

            if (ItemHoursSince2013 - TodayHoursSince2013 <= 24)
            {
                TotalCost += Program.TransactionList[i].TotalCost;
                TotalEarned += Program.TransactionList[i].TotalEarned;
                TotalProfit += Program.TransactionList[i].TotalEarned - Program.TransactionList[i].TotalCost;
                TotalHST += Program.TransactionList[i].TotalHST;
            }
        }
        label6.Text = "$" + String.Format("{0:0.00}", TotalCost);
        label7.Text = "$" + String.Format("{0:0.00}", TotalEarned);
        label8.Text = "$" + String.Format("{0:0.00}", TotalProfit);
        label10.Text = "$" + String.Format("{0:0.00}", TotalHST);
    }
4

1 回答 1

2

将它放在你的 for 循环中(现在将 datetime 变量放在外面):

DateTime now = DateTime.Now;
DateTime TransactionListDate = Program.TransactionList[i].HoursSince2013;
if (TransactionListDate > now.AddHours(-24) && TransactionListDate <= now)
{
    //it falls between now and last 24 hours....
}

我认为这是您需要的。我假设 Program.TransactionList[i].HoursSince2013 是日期时间。

于 2013-10-26T15:51:21.690 回答