C# || How To Generate Hourly Time Range With Minute Interval Using C#
The following is a module with functions which demonstrates how to generate an hourly time range with minute interval between a start and end time using C#.
The function demonstrated in this page generates a time value list containing the time from a starting hour to an ending hour, separated by a minute step. The starting and ending hour is an integer from 0 through 23 representing the 24 hour period of the day, and the minute step can be any minute interval, including decimal values.
The starting and ending hours can also be flipped, indicating that the results should be returned in descending order.
An optional parameter also exists which allows to tune the results. When the range is in ascending order, the parameter indicates that the results should exclude/include the entire ending hour. When the range is in descending order, the parameter indicates that the results should exclude/include the entire starting hour.
1. Ascending Time Range – Minute Interval – Default
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a minute interval in ascending order.
In this example, the default options are used, which excludes the full ending hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Ascending Time Range - Minute Interval - Default // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result = Utils.DateRange.GetTimeRange(0, 23, 15.5); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString()}"); } // expected output: /* Time: 1/1/0001 12:00:00 AM, String: 12:00:00 AM Time: 1/1/0001 12:15:30 AM, String: 12:15:30 AM Time: 1/1/0001 12:31:00 AM, String: 12:31:00 AM Time: 1/1/0001 12:46:30 AM, String: 12:46:30 AM Time: 1/1/0001 1:02:00 AM, String: 1:02:00 AM Time: 1/1/0001 1:17:30 AM, String: 1:17:30 AM Time: 1/1/0001 1:33:00 AM, String: 1:33:00 AM Time: 1/1/0001 1:48:30 AM, String: 1:48:30 AM .... .... .... .... Time: 1/1/0001 9:11:00 PM, String: 9:11:00 PM Time: 1/1/0001 9:26:30 PM, String: 9:26:30 PM Time: 1/1/0001 9:42:00 PM, String: 9:42:00 PM Time: 1/1/0001 9:57:30 PM, String: 9:57:30 PM Time: 1/1/0001 10:13:00 PM, String: 10:13:00 PM Time: 1/1/0001 10:28:30 PM, String: 10:28:30 PM Time: 1/1/0001 10:44:00 PM, String: 10:44:00 PM Time: 1/1/0001 10:59:30 PM, String: 10:59:30 PM */ |
2. Descending Time Range – Hourly Interval – Default
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a hourly interval in descending order.
In this example, the default options are used, which excludes the full starting hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Descending Time Range - Hourly Interval - Default // Get an hour range from 10PM - 10AM, with a 2 hour interval var result = Utils.DateRange.GetTimeRange(22, 10, 120); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString(true)}"); } // expected output: /* Time: 1/1/0001 10:00:00 PM, String: 10 PM Time: 1/1/0001 8:00:00 PM, String: 8 PM Time: 1/1/0001 6:00:00 PM, String: 6 PM Time: 1/1/0001 4:00:00 PM, String: 4 PM Time: 1/1/0001 2:00:00 PM, String: 2 PM Time: 1/1/0001 12:00:00 PM, String: 12 PM Time: 1/1/0001 10:00:00 AM, String: 10 AM */ |
3. Ascending Time Range – Minute Interval – Include Full Hour
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a minute interval in ascending order.
In this example, the optional parameter is used, which includes the full ending hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Ascending Time Range - Minute Interval - Include Full Hour // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result = Utils.DateRange.GetTimeRange(0, 23, 15.5, true); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString()}"); } // expected output: /* Time: 1/1/0001 12:00:00 AM, String: 12:00:00 AM Time: 1/1/0001 12:15:30 AM, String: 12:15:30 AM Time: 1/1/0001 12:31:00 AM, String: 12:31:00 AM Time: 1/1/0001 12:46:30 AM, String: 12:46:30 AM Time: 1/1/0001 1:02:00 AM, String: 1:02:00 AM Time: 1/1/0001 1:17:30 AM, String: 1:17:30 AM Time: 1/1/0001 1:33:00 AM, String: 1:33:00 AM Time: 1/1/0001 1:48:30 AM, String: 1:48:30 AM .... .... .... .... Time: 1/1/0001 10:13:00 PM, String: 10:13:00 PM Time: 1/1/0001 10:28:30 PM, String: 10:28:30 PM Time: 1/1/0001 10:44:00 PM, String: 10:44:00 PM Time: 1/1/0001 10:59:30 PM, String: 10:59:30 PM Time: 1/1/0001 11:15:00 PM, String: 11:15:00 PM Time: 1/1/0001 11:30:30 PM, String: 11:30:30 PM Time: 1/1/0001 11:46:00 PM, String: 11:46:00 PM */ |
4. Descending Time Range – Hourly Interval – Include Full Hour
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a hourly interval in descending order.
In this example, the optional parameter is used, which includes the full starting hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Descending Time Range - Hourly Interval - Include Full Hour // Get an hour range from 10PM - 10AM, with a 2 hour interval var result = Utils.DateRange.GetTimeRange(22, 10, 120, true); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString(true)}"); } // expected output: /* Time: 1/1/0001 10:59:00 PM, String: 10:59 PM Time: 1/1/0001 8:59:00 PM, String: 8:59 PM Time: 1/1/0001 6:59:00 PM, String: 6:59 PM Time: 1/1/0001 4:59:00 PM, String: 4:59 PM Time: 1/1/0001 2:59:00 PM, String: 2:59 PM Time: 1/1/0001 12:59:00 PM, String: 12:59 PM Time: 1/1/0001 10:59:00 AM, String: 10:59 AM */ |
5. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Collections.Generic; namespace Utils { public class DateRange { public DateTime Time { get; set; } protected bool showSeconds = false; public string ToString(bool condensed = false) { var str = Time.ToShortTimeString(); if (condensed) { str = str.Replace(":00", string.Empty); } else if (showSeconds) { str = Time.ToString("h:mm:ss tt"); } return str; } /// <summary> /// Generates a time value list containing the time from 'Starting Hour' /// to 'Ending Hour' separated by 'Minute Step'. 'Starting Hour' and 'Ending Hour' /// should be an integer from 0 through 23 representing the hour of the day. /// </summary> /// <param name="startingHour">The starting hour from 0 through 23</param> /// <param name="endingHour">The ending hour from 0 through 23</param> /// <param name="minuteStep">The minute step</param> /// <param name="includeFullHour">If going in ascending direction, indicates /// the results should include the entire 'Ending Hour'. If going in descending /// direction, indicates the results should include the entire 'Starting Hour'</param> /// <returns>The time value list from 'Starting Hour' to 'Ending Hour'</returns> public static List<DateRange> GetTimeRange(int startingHour, int endingHour , double minuteStep, bool includeFullHour = false) { var result = new List<DateRange>(); var maxHour = 23; var minHour = 0; var maxMinute = 59; var minMinute = 0; var startingMinute = minMinute; var endingMinute = maxMinute; var showSeconds = (int)minuteStep != minuteStep; if (minuteStep < 0) { minuteStep = 1; } // Flip results if going in opposite direction if (startingHour > endingHour) { minuteStep *= -1; startingMinute = maxMinute; endingMinute = minMinute; startingHour = Math.Min(startingHour, maxHour); endingHour = Math.Max(endingHour, minHour); } else { startingHour = Math.Max(startingHour, minHour); endingHour = Math.Min(endingHour, maxHour); } if (!includeFullHour) { startingMinute = 0; endingMinute = 0; } var today = DateTime.Today; var startTime = today.SetTime(Convert.ToDateTime($"{startingHour.ToString("00")}:{startingMinute.ToString("00")}")); var endTime = today.SetTime(Convert.ToDateTime($"{endingHour.ToString("00")}:{endingMinute.ToString("00")}")); var currentTime = startTime; while (startingHour < endingHour ? currentTime <= endTime : currentTime >= endTime) { result.Add(new DateRange() { Time = new DateTime(1, 1, 1).SetTime(currentTime), showSeconds = showSeconds }); currentTime = currentTime.AddMinutes(minuteStep); } return result; } } public static class Extensions { /// <summary> /// Appends a date and time value together /// </summary> /// <param name="date">The date portion</param> /// <param name="time">The time portion</param> /// <returns>The appended date and time value</returns> public static DateTime SetTime(this DateTime date, DateTime time) { return date.Date.Add(time.TimeOfDay); } } }// http://programmingnotes.org/ |
6. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result = Utils.DateRange.GetTimeRange(0, 23, 15.5); foreach (var value in result) { Display($"Time: {value.Time}, String: {value.ToString()}"); } Display(""); // Get an hour range from 10PM - 10AM, with a 2 hour interval var result2 = Utils.DateRange.GetTimeRange(22, 10, 120); foreach (var value in result2) { Display($"Time: {value.Time}, String: {value.ToString(true)}"); } Display(""); // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result3 = Utils.DateRange.GetTimeRange(0, 23, 15.5, true); foreach (var value in result3) { Display($"Time: {value.Time}, String: {value.ToString()}"); } Display(""); // Get an hour range from 10PM - 10AM, with a 2 hour interval var result4 = Utils.DateRange.GetTimeRange(22, 10, 120, true); foreach (var value in result4) { Display($"Time: {value.Time}, String: {value.ToString(true)}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply