C # Is there a way to make a time range list? configurable

Is there a way to list the time range? For example: A list containing: 12:00 to 13:00 From 1:00 to 14:00, etc ... Where the partition section is the configuration. I think you should use datetime and divide it by a specific number (in this case, one hour)

Can someone point me in the right direction or provide me with an example?

Thanks in advance!

+5
source share
1 answer

There is no built-in type that defines a time range, but it would be quite easy to create it by combining DateTimeand TimeSpan. For instance:

struct TimeRange
{
    private readonly DateTime start;
    private readonly TimeSpan duration;

    public TimeRange ( DateTime start, TimeSpan duration )
    {
        this.start = start;
        this.duration = duration;
    }
}

List<TimeRange> DateTime TimeSpan . , TimeRange, Split, IEnumerable<TimeRange> TimeRange .

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);
    }
}

- :

TimeRange mainRange = new TimeRange(DateTime.Now, new TimeSpan(12, 0, 0));
List<TimeRange> rangeList = mainRange.Split(new TimeSpan(1, 0, 0)).ToList();

12 1 , .

** **

, . , Split , , - . . - , .

TimeRange.CreateList, List<TimeRange> .

+6

All Articles