Friday, July 13, 2012

c# - Generate rolling half hour time slots for the last 24 hours

In my previous post I posted code to generate half hour timeslots for a given day.One of the developers in my team was working on a application that needed half hour timeslots for rolling 24 hours instead of a given day.The code to achieve this is essentially same except that the oCurrentDate is set to Date.Now.AddDays(-1).

try
            {
                DateTime oCurrentDate = DateTime.Now.AddDays(-1);
                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: