Ad

AddHour / AddMinute Store Within A ListItem

- 1 answer

I am using c#.net

I have two times pulled from a database (‘earliest start time’ and ‘latest end time’).

I want to loop through and add ‘in-between’ times to a list.

Example

  • earliest start time – 12:00
  • 12:30
  • 13:00
  • 13:30
  • 14:00
  • 14:30
  • latest end time – 15:00

I have found some code, but as the information is being pulled from a database the start time could be 12:00/12:30 etc. I don’t know how to adapt the below code to expect both times (full hour / half an hour)

int i = -1; 

List<string> appointmentTimes = new List<string>();

while (DateTime.Today.AddHours(firstTime).AddMinutes(i * 30).Hour < lastTime)
{
appointmentTimes.Add(DateTime.Today.AddHours(7).AddMinutes(30*(++i)); );
}

Would I have to split the firstTime into hours/mintues?

Example

while (DateTime.Today.AddHours(firstTimeHour).AddMinutes(firstTimeMintues, i * 30).Hour < lastTime)
{
appointmentTimes.Add(DateTime.Today.AddHours(7).AddMinutes(30*(++i)); );
}

Thanks in advance for any help.

Clare

Ad

Answer

Thanks Justin for putting me on the right track.

            // ---- Create a new list
            List<string> appointmentTimes = new List<string>();

            // ---- If information is pulled back
            if (myResults != null)
            {
                TimeSpan time = TimeSpan.FromMinutes(30);

                DateTime FirstTime = Convert.ToDateTime(myResult.firstStart);
                DateTime LatestTime = Convert.ToDateTime(myResult.lastEnd);

                while (FirstTime < LatestTime )
                {
                    appTimes.Add(FirstTime .ToString());
                    FirstTime += time;
                }
            }
Ad
source: stackoverflow.com
Ad