Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get interval between hours and put into list from start into finish?

Tags:

For example, I will be given a time on hours with type DateTime hours like this

for the starter

  1. my starttime is 00:00
  2. endtime is 02:00

and every time 30 minutes I like to input the value into a List<DateTime> so, how can I get the value to put into a list that is look like this?

  • 00:00
  • 00:30
  • 01:00
  • 01:30
  • 02:00

My Code

        DateTime starTime = new DateTime();
        DateTime endTimes = new DateTime();
        DateTime interval = new DateTime();
        List<DateTime> intervals = new List<DateTime>();
        starTime = DateTime.ParseExact(fulldate + "00:00",
                                "yyyy/MM/dd HH:mm",
                                CultureInfo.InvariantCulture);
        endTimes = DateTime.ParseExact(fulldate + "02:00",
                                "yyyy/MM/dd HH:mm",
                                CultureInfo.InvariantCulture); ;
        interval = starTime;
        for (int i = 0; i < 24; i++)
        {
            interval.AddHours(0.5);
            intervals.Add(interval);
            if (interval.ToString("HH:mm") == endTimes.ToString("HH:mm"))
            {
                break;
            }
        }

Can anyone help me to solve this?

like image 663
Ricky Reza Muhammad Avatar asked Mar 14 '21 12:03

Ricky Reza Muhammad


1 Answers

With some assumption (that end time is on the same day, that your end time is always something that can be devided by 30 mins, ...) this would work.

var start = new TimeSpan(0, 0, 0);
var end = new TimeSpan(2, 0, 0);
var current = start;

List<DateTime> values = new List<DateTime>();
var startDate = DateTime.Now.Date; // editited after @pinkflowydx33's comment 

values.Add(startDate + start);

while (current < end)
{
    current = current.Add(new TimeSpan(0, 30, 0));
    values.Add(startDate + current);
}

foreach (var v in values)
{
    Console.WriteLine(v);
}
like image 167
gsharp Avatar answered Jan 04 '23 16:01

gsharp