检查DateTime值是否超过N天

时间:2015-06-19 17:37:03

标签: c# asp.net asp.net-mvc algorithm asp.net-mvc-4

我有一个程序,用于删除我的T-SQL数据库中超过指定天数的项目。它开始像

    [HttpPost]
    public ActionResult FlushLinks (string numDaysOld)
    {
        // Deletes all database references to links were submitted over numDaysOld days ago

        DateTime currentDateTime = DateTime.Now;
        foreach (LinkDate thisLinkDate in PD.dates)
        {
            TimeSpan thisTimeSpan = new TimeSpan(Convert.ToInt16(numDaysOld), 0, 0, 0);
            if ((currentDateTime - thisLinkDate.dtime) > thisTimeSpan)
            {
                foreach (AssetLink thislink in PD.links) if (thislink.linkguid == thisLinkDate.linkguid) PD.links.DeleteOnSubmit(thislink);

但由于某些原因无效,因为当我使用numDaysOld=30调用它时,它删除了所有内容,包括带有2015-06-18 16:36:002015-06-18 16:10:00等最新戳记的项目{1}}在我的数据库中)

我的手术有什么明显的错误吗?

1 个答案:

答案 0 :(得分:0)

为什么不通过使用DateTime.AddDays()函数比较日期,因为它是您特别感兴趣的日期的一部分。这里' sa小例子。

class Program
{
    static void Main(string[] args)
    {
        int limitDays = 5;
        DateTime[] dates = 
        {
            DateTime.Now.AddDays(-1), // falls within 5 days.
            DateTime.Now.AddDays(-10) // does not fall within 5 days.
        };

        Console.WriteLine("Limit: " + DateTime.Now.AddDays(-limitDays).ToString() + " (" + limitDays.ToString() + " days)");
        Console.WriteLine();

        foreach (var date in dates)
        {
            if (DateTime.Compare(date, DateTime.Now.AddDays(-limitDays)) < 0)
            {
                Console.WriteLine("Outside the limit: " + date.ToString());
            }
            else if (DateTime.Compare(date, DateTime.Now.AddDays(-limitDays)) >= 0)
            {
                Console.WriteLine("Within the limit: " + date.ToString());
            }
        }


        Console.ReadLine();

    }
}