AddHour / AddMinute store within a ListItem
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(firstTimeMintue开发者_StackOverflow社区s, i * 30).Hour < lastTime)
{
appointmentTimes.Add(DateTime.Today.AddHours(7).AddMinutes(30*(++i)); );
}
Thanks in advance for any help.
Clare
Sorry, just a hint rather than an answer but it will probably be easier to use TimeSpan to loop through the available times.
Use TimeSpan.FromHours and TimeSpan.FromMinutes to get a TimeSpan and then increment 30 to it adding to the list similar to how you're doing is with TimeSpan.Hours and TimeSpan.Minutes.
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;
}
}
精彩评论