Is there a way to make a list of time range? For example: A list containing: 12:00 to 1:00 pm 1:00 to 2:00 pm etc... Where the dividing section is configuration. I think you have to use datetime and divide it to a certain number(in this case one hour)
Could someone please point me to the right direction or provide me an example?
Thanks in advance!
There's no built-in type that defines a time-range but it would be pretty easy to create one by combining a DateTime
and a TimeSpan
. For example:
struct TimeRange
{
private readonly DateTime start;
private readonly TimeSpan duration;
public TimeRange ( DateTime start, TimeSpan duration )
{
this.start = start;
this.duration = duration;
}
}
You could then build a List<TimeRange>
using a specific DateTime
as the starting point and adding the required TimeSpan
for each element. For example, here's a very basic implementation of TimeRange
including a method called Split
which returns an IEnumerable<TimeRange>
based on the current TimeRange
and the required duration of the sub-ranges.
struct TimeRange
{
private readonly DateTime start;
private readonly TimeSpan duration;
public TimeRange ( DateTime start, TimeSpan duration )
{
this.start = start;
this.duration = duration;
}
public DateTime From { get { return start; } }
public DateTime To { get { return start + duration; } }
public TimeSpan Duration { get { return duration; } }
public IEnumerable<TimeRange> Split (TimeSpan subDuration)
{
for (DateTime subRangeStart = From; subRangeStart < this.To; subRangeStart += subDuration)
{
yield return new TimeRange(subRangeStart, subDuration);
}
}
public override string ToString()
{
return String.Format ("{0} -> {1}", From, To);
}
}
You can then do something like this:
TimeRange mainRange = new TimeRange(DateTime.Now, new TimeSpan(12, 0, 0));
List<TimeRange> rangeList = mainRange.Split(new TimeSpan(1, 0, 0)).ToList();
This will give a list of 12 time ranges of 1-hour duration starting from the current time.
** Update **
Note that the above implementation is VERY basic. The Split
method, for example, will happily produce a lits of ranges where the end of the last sub-range is beyond the end of the parent range if the sub duration is not an integral division of the parent range. It would be hard to add checks for this kind of thing, though. The real question is what you want to happen in those kind of scenarios.
It would also be very easy to create a static TimeRange.CreateList
method that builds a List<TimeRange>
without the need for an explicit parent range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With