Friday, July 13, 2012

c# - Generate half hour timeslots for a given date

In one of my previous posts, I had posted sql to generate half hour timeslots.Here's the same in C#.

Note: I am using the date July 10,2012

try
{
      DateTime oCurrentDate = new DateTime(2012, 7, 10);                  
      DateTime oTimeSlot = new DateTime();

      if (oCurrentDate.Minute > 30)

           oTimeSlot = new DateTime(oCurrentDate.Year, oCurrentDate.Month, oCurrentDate.Day, oCurrentDate.Hour, 30, 0);
      else
           oTimeSlot = new DateTime(oCurrentDate.Year, oCurrentDate.Month, oCurrentDate.Day, oCurrentDate.Hour, 0, 0);

      for (Int32 iCounter = 1; iCounter <= 48; iCounter++)

      {
            Console.WriteLine("Day: " + oTimeSlot.DayOfWeek.ToString() + ", " + oTimeSlot.ToString("m") + " Time: " + oTimeSlot.ToString("t") + " - " + oTimeSlot.AddMinutes(30).ToString("t"));
                   
            oTimeSlot = oTimeSlot.AddMinutes(30);               
      }
}
catch (Exception ex)
{
      Console.WriteLine(ex.Message);
}

Output:



No comments: