user2176764
user2176764

Reputation: 87

How to divide time in equal slots in C#

I want to divide time in equal intervals in C#. Like from 3:00pm to 6:00pm create time intervals with a gap of 45 minutes (e.g, 3:00pm, 3:45pm, 4:30pm .... 6:00pm. How can I acheive this in C# ?

Upvotes: 2

Views: 5244

Answers (3)

BobbyA
BobbyA

Reputation: 2260

You can use the DateTime.Ticks property to define your intervals, and then create a series of DateTime objects based on your defined interval. The example below can be run in LINQpad. Per the documentation, there are 10000000 ticks in one second. With that in mind:

var startTS = Convert.ToDateTime("6/17/2018 15:00:00");
var endTS = Convert.ToDateTime("6/17/2018 18:00:00");

long ticksPerSecond = 10000000;
long ticksPerMinute = ticksPerSecond * 60;
long ticksPer45Min = ticksPerMinute * 45;
long startTSInTicks = startTS.Ticks;
long endTsInTicks = endTS.Ticks;

for(long i = startTSInTicks; i <= endTsInTicks; i+=ticksPer45Min)
{
    new DateTime(i).Dump();
}

In LINQpad, the output looks like this:

6/17/2018 15:00:00
6/17/2018 15:45:00
6/17/2018 16:30:00
6/17/2018 17:15:00

Upvotes: 3

npinti
npinti

Reputation: 52185

Datetime.AddMinutes(double value) should do what you are looking for. Just keep on adding until the result of the addition goes over the maximum date/time you have.

NOTE: This assumes you know your interval. If, on the other hand, you require to split a time span in a equal n parts you would require a different approach, as shown here.

Upvotes: 1

Rohit
Rohit

Reputation: 10236

Try this

        DateTime StartTime = DateTime.Parse("3:0:0");//If pm it should be 15
        DateTime EndTime = DateTime.Parse("6:0:0");//If pm it should be 18
        while (StartTime!=EndTime)
        {
            double minuts = +45;
            StartTime = StartTime.AddMinutes(minuts);
        }

Hope this helps

Upvotes: 1

Related Questions