C#实现判断一个时间点是否位于给定时间区间的方法
发布时间:2020-12-15 05:53:06 所属栏目:百科 来源:网络整理
导读:本篇章节讲解C#实现判断一个时间点是否位于给定时间区间的方法。供大家参考研究。具体如下: 本文中实现了函数 复制代码 代码如下: static bool isLegalTime(DateTime dt,string time_intervals); 给定一个字符串表示的时间区间time_intervals: 1)
本篇章节讲解C#实现判断一个时间点是否位于给定时间区间的方法。分享给大家供大家参考。具体如下: 本文中实现了函数 复制代码 代码如下: static bool isLegalTime(DateTime dt,string time_intervals); 给定一个字符串表示的时间区间time_intervals: 1)每个时间点用六位数字表示:如12点34分56秒为123456 2)每两个时间点构成一个时间区间,中间用字符'-'连接 3)可以有多个时间区间,不同时间区间间用字符';'隔开 例如:"000000-002559;030000-032559;060000-062559;151500-152059" 若DateTime类型数据dt所表示的时间在字符串time_intervals中, 则函数返回true,否则返回false 示例程序代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //使用正则表达式 using System.Text.RegularExpressions; namespace TimeInterval { class Program { static void Main(string[] args) { Console.WriteLine(isLegalTime(DateTime.Now,"000000-002559;030000-032559;060000-062559;151500-152059")); Console.ReadLine(); } /// <summary> /// 判断一个时间是否位于指定的时间段内 /// </summary> /// <param name="time_interval">时间区间字符串</param> /// <returns></returns> static bool isLegalTime(DateTime dt,string time_intervals) { //当前时间 int time_now = dt.Hour * 10000 + dt.Minute * 100 + dt.Second; //查看各个时间区间 string[] time_interval = time_intervals.Split(';'); foreach (string time in time_interval) { //空数据直接跳过 if (string.IsNullOrWhiteSpace(time)) { continue; } //一段时间格式:六个数字-六个数字 if (!Regex.IsMatch(time,"^[0-9]{6}-[0-9]{6}$")) { Console.WriteLine("{0}: 错误的时间数据",time); } string timea = time.Substring(0,6); string timeb = time.Substring(7,6); int time_a,time_b; //尝试转化为整数 if (!int.TryParse(timea,out time_a)) { Console.WriteLine("{0}: 转化为整数失败",timea); } if (!int.TryParse(timeb,out time_b)) { Console.WriteLine("{0}: 转化为整数失败",timeb); } //如果当前时间不小于初始时间,不大于结束时间,返回true if (time_a <= time_now && time_now <= time_b) { return true; } } //不在任何一个区间范围内,返回false return false; } } } 当前时间为2015年8月15日 16:21:31,故程序输出为False 希望本文所述对大家的C#程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |