在两个日期时间之间出现多少次

时间:2011-10-10 19:20:25

标签: c# asp.net-mvc asp.net-mvc-3 datetime

---- ---- EDIT

哦,对不起,这是一个巨大的错误:)

让我再问这个问题......

以下是一个例子,

Datetime startTime = 2011-10-08 12:30:00
Datetime endTime = 2011-10-10 15:00:00

在两个日期时间之间发生了多少次12:00:00 - 13:00:00?

2011-10-08 12:30:00 - 2011-10-08 13:00:00 Not Ok (time has alredy started)
2011-10-09 12:00:00 - 2011-10-09 13:00:00 Ok
2011-10-10 12:00:00 - 2011-10-10 13:00:00 Ok

期待结果2.

提前致谢!

3 个答案:

答案 0 :(得分:4)

(endTime-startTime).Ticks/timeSpan.Ticks

答案 1 :(得分:1)

取两天的差值除以间隔。

TimeSpan timeSpan = new TimeSpan(24, 00, 00); // one day

DateTime start = new DateTime(2011, 10, 08, 11, 00, 00);
DateTime end = new DateTime(2011, 10, 10, 23, 00, 00); // 2 and 1/2 days later

var occurances = ((end - start).Ticks / (float)timeSpan.Ticks); // 2.5f

答案 2 :(得分:1)

在看到您的更新后,您将需要执行一些操作,例如确定要检查的天数并执行边界检查以查看特定时间是否在您的开始日期和结束日期之内。作为一个想法,这里是一些示例代码,我把它放在一起。

    private static void CheckTimes()
    {
        DateTime start = DateTime.Parse("2011-10-08 12:30:00");
        DateTime end = DateTime.Parse("2011-10-10 15:00:00");
        // variable to use for bound checking (Date property sets the hour to 00)
        DateTime boundscheck = start.Date;
        // variable containing results
        int timesFound = 0;

        // This loop assumes we are only looking for one match per day
        for (int i = 0; i <= (end - start).Days; i++)
        {
            // set the lower bound to yyyy-mm-dd 12:00:00
            var lowerbound = boundscheck.Date.AddHours(12);
            // set the upper bound to yyyy-mm-dd 13:00:00
            var upperbound = lowerbound.AddHours(1);
            //determine if bounds are within our start and end date
            if (lowerbound >= start && upperbound <= end)
            {
                timesFound++;
            }
            // increment boundscheck variable by one day
            boundscheck = boundscheck.AddDays(1);
        }
    }

希望这有帮助。