This article example describes the method of C# to determine whether a time point is in a given time interval. Share it for your reference. The details are as follows:
Functions are implemented in this article
Given a string representing time_intervals:
1) Each time point is represented by six digits: for example, 12:34:56 seconds is 123456
2) Every two time points form a time interval, and the character '-' is connected in the middle.
3) There can be multiple time intervals, and different time intervals are separated by characters ';'
For example: "000000-002559;030000-032559;060000-062559;151500-152059"
If the time represented by the DateTime type data dt is in the string time_intervals,
The function returns true, otherwise it returns false
Sample program code:
using System; using ; using ; using ; using ; //Use regular expressionusing ; namespace TimeInterval { class Program { static void Main(string[] args) { (isLegalTime(, "000000-002559;030000-032559;060000-062559;151500-152059")); (); } /// <summary> /// Determine whether a time is within a specified time period /// </summary> /// <param name="time_interval">Time interval string</param> /// <returns></returns> static bool isLegalTime(DateTime dt, string time_intervals) { //Current time int time_now = * 10000 + * 100 + ; //View each time interval string[] time_interval = time_intervals.Split(';'); foreach (string time in time_interval) { // Skip the empty data directly if ((time)) { continue; } //Format for a period of time: six numbers-six numbers if (!(time, "^[0-9]{6}-[0-9]{6}$")) { ("{0}: Incorrect time data", time); } string timea = (0, 6); string timeb = (7, 6); int time_a, time_b; //Try to convert to integer if (!(timea, out time_a)) { ("{0}: Failed to convert to integer", timea); } if (!(timeb, out time_b)) { ("{0}: Failed to convert to integer", timeb); } //If the current time is not less than the initial time and not greater than the end time, return true if (time_a <= time_now && time_now <= time_b) { return true; } } //Not within any interval range, return false return false; } } }
The current time is August 15, 2015 at 16:21:31, so the program output is False
I hope this article will be helpful to everyone's C# programming.