按日期排序时出现问题

本文关键字:问题 日期 排序 | 更新日期: 2023-09-27 18:36:55

我尝试仅显示 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);
    }

按日期排序时出现问题

把它放在你的 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]。小时自2013年以来是日期时间。