2

我有开始时间、结束时间和持续时间。我想在开始时间添加持续时间,直到在 c# 中达到结束时间?

例如开始时间是09:00:00

结束时间是15:00:00,持续时间间隔是 20 分钟

我需要这种输出:

09:00:00-09:20:00
09:20:00-09:40:00
09:40:00-10:00:00

并将其绑定到gridview

4

5 回答 5

4

This method would do that:

static IEnumerable<DateTime> Spend(DateTime startTime, DateTime endTime, TimeSpan duration)
{
    while (startTime <= endTime)
    {
        yield return startTime;
        startTime = startTime.Add(duration);
    }
}

And sample usage would be:

foreach (var time in Spend(DateTime.Now, DateTime.Now.AddHours(5), TimeSpan.FromMinutes(20)))
    Console.WriteLine(time);
于 2013-05-29T14:20:46.933 回答
1

使用TimeSpans,您可以:

TimeSpan startTime = new TimeSpan(0, 9, 0, 0);
TimeSpan endTime = new TimeSpan(0, 15, 0, 0);
TimeSpan counter = startTime;
TimeSpan durationPeriod = new TimeSpan(0, 20, 0);
List<string> durations = new List<string>();

while (counter < endTime)
{
    durations.Add(counter.ToString() + "-" + counter.Add(durationPeriod));
    counter = counter.Add(durationPeriod);
}

foreach (var duration in durations)
{
    Console.WriteLine(duration + Environment.NewLine);
}

输出:

时间跨度

于 2013-05-29T14:19:41.370 回答
0

When you use the - binary operator with two DateTime objects, you get a TimeSpan.

So you could do this:

TimeSpan t = end - start;

You can then add that TimeSpan back to a DateTime as many times as you want. For example, to add that interval three times to the start time:

for (int i = 0; i < 3; i++)
{
    start = start.Add(t);
}

The Add method does not modify the DateTime, so that's why we assign it to the return of its method.

Now all you have to do is fetch the DateTime's from the database and apply this to them.

Edit: I see that the interval you want to add multiple times is not the difference between the start and end times. So you could do something like this:

DateTime start = new DateTime(2013, 5, 29, 0, 9, 0);
DateTime end = new DateTime(2013, 5, 29, 15, 0, 0);

TimeSpan interval = new TimeSpan(0, 20, 0 0); // 20 minutes
for (DateTime temp = start; temp < end; temp = temp.Add(interval))
{
    // Here you output temp, such as:
    Console.WriteLine (temp.ToShortTimeString() + " - " + temp.Add(interval).ToShortTimeString());
}
于 2013-05-29T14:18:25.527 回答
0
var startTime = new TimeSpan(9, 0, 0);
while (startTime <= new TimeSpan(15, 0, 0)) {
    var endTime = startTime + new TimeSpan(0, 20, 0);
    Console.WriteLine(string.Format("{0}-{1}", startTime, endTime));
    startTime = endTime;
}
于 2013-05-29T14:21:05.090 回答
0
var dates = new List<DateTime>();

for (var dt = start; dt <= end; dt = dt.AddMinutes(gap))
{
   dates.Add(dt);
}

//  bind the gridview using dates 
于 2013-05-29T14:52:58.197 回答