计算开始时间,结束时间 中间间隔毫秒数

        /// <summary>
        /// 距离下一个运行时间还需sleep多少毫秒
        /// </summary>
        /// <returns></returns>
        public static int SleepMilliseconds()
        {
            DateTime NowDate = DateTime.Now;
            string nowDate = NowDate.ToString("yyyy-MM-dd");
            string startTime = nowDate + " " + Config.StartTime;
            string endTime = nowDate + " " + Config.EndTime;
            string finishTime = nowDate + " " + "23:59:59";

            DateTime StartTime = DateTime.Parse(startTime);
            DateTime EndTime = DateTime.Parse(endTime);
            DateTime FinishTime = DateTime.Parse(finishTime);

            TimeSpan A, B;
            if (DateTime.Compare(StartTime, EndTime) < 0)
            {
                //开始时间早于结束时间   开始时间 ~ 结束时间
                if (DateTime.Compare(StartTime, NowDate) <= 0 && DateTime.Compare(NowDate, EndTime) <= 0)
                {
                    return 0;
                }
                else if (DateTime.Compare(NowDate, StartTime) < 0)
                {
                    A = new TimeSpan(StartTime.Ticks);
                    B = new TimeSpan(NowDate.Ticks);
                    return (int)A.Subtract(B).Duration().TotalMilliseconds;
                }
                else
                {
                    A = new TimeSpan(StartTime.AddDays(1).Ticks);
                    B = new TimeSpan(NowDate.Ticks);
                    return (int)A.Subtract(B).Duration().TotalMilliseconds;
                }
            }
            else 
            {
                //开始时间大于结束时间   开始时间 ~ 23:59:59  和  00:00:01  ~ 结束时间
                if (DateTime.Compare(StartTime, NowDate) <= 0 || DateTime.Compare(NowDate, EndTime) <= 0)
                {
                    return 0;
                }
                else
                {
                    A = new TimeSpan(StartTime.Ticks);
                    B = new TimeSpan(NowDate.Ticks);
                    return (int)A.Subtract(B).Duration().TotalMilliseconds;
                }
            }
        }


posted @ 2014-08-28 23:53  _Jesse  阅读(506)  评论(0编辑  收藏  举报