查詢正序排列的List中缺失的日期資料的一個演算法

滄海一滴發表於2013-11-15

Code:

        public List<DateTime> getMissDateData()
        {

            DateTime[] keys = { DateTime.Now.AddDays(-5), DateTime.Now.AddDays(-3), DateTime.Now.AddDays(-1), };
            List<DateTime> missingDate = new List<DateTime>();
            for (int i = 0; i < keys.Length; i++)
            {
                logger.Info("Orginal data:"+keys[i]);
            }

            if (keys.Length > 0)
            {
                DateTime firstDate = keys[0];
                if (firstDate.Day > 1)
                {
                    int missingDateInt = firstDate.Day - 1;
                    for (int i = missingDateInt; i > 0; i--)
                    {
                        missingDate.Add(firstDate.AddDays(-i));
                    }
                }
                int keysLength = (keys[keys.Length - 1] - keys[0]).Days;

                DateTime dtTemp = keys[0];
                // firstDate = keys[0];
                int count = keys.Length;
                for (int i = 0; i < count; i++)
                {
                    Console.WriteLine(dtTemp.ToString(keys[i].ToString("yyyy-MM-dd HH:mm:ss")));
                    while (DateTime.Compare(keys[i], dtTemp) != 0)
                    {
                        logger.InfoFormat("Actual Date:{0};  The date of the cumulative:{1}", keys[i].ToShortDateString(), dtTemp.ToShortDateString());
                        logger.InfoFormat("{0}", DateTime.Compare(keys[i], dtTemp));
                        //Console.WriteLine(String.Format("Actual Date:{0};  The date of the cumulative:{1}", keys[i].ToShortDateString(), dtTemp.ToShortDateString()));
                       // Console.WriteLine(String.Format("{0}", DateTime.Compare(keys[i], dtTemp)));
                        missingDate.Add(dtTemp);
                        dtTemp = dtTemp.AddDays(1);
                    }
                    dtTemp = dtTemp.AddDays(1);
                }
            }
            else
            {
                logger.InfoFormat("Has no new data:{0}", keys.Length);
               // Console.WriteLine(String.Format("Has no new data:{0}", keys.Length));
            }

            for (int i = 0; i < missingDate.Count; i++)
            {
                logger.Info("Missing data:" + missingDate[i].ToShortDateString());
                //Console.WriteLine("Missing data:" + missingDate[i].ToShortDateString());
            }
            return missingDate;
        }
歡迎大家吐槽。

相關文章