C#实现判断一个时间点是否位于给定时间区间的方法
本文实例讲述了C#实现判断一个时间点是否位于给定时间区间的方法。分享给大家供大家参考。具体如下:
本文中实现了函数
staticboolisLegalTime(DateTimedt,stringtime_intervals);
给定一个字符串表示的时间区间time_intervals:
1)每个时间点用六位数字表示:如12点34分56秒为123456
2)每两个时间点构成一个时间区间,中间用字符'-'连接
3)可以有多个时间区间,不同时间区间间用字符';'隔开
例如:"000000-002559;030000-032559;060000-062559;151500-152059"
若DateTime类型数据dt所表示的时间在字符串time_intervals中,
则函数返回true,否则返回false
示例程序代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
//使用正则表达式
usingSystem.Text.RegularExpressions;
namespaceTimeInterval
{
classProgram
{
staticvoidMain(string[]args)
{
Console.WriteLine(isLegalTime(DateTime.Now,
"000000-002559;030000-032559;060000-062559;151500-152059"));
Console.ReadLine();
}
///<summary>
///判断一个时间是否位于指定的时间段内
///</summary>
///<paramname="time_interval">时间区间字符串</param>
///<returns></returns>
staticboolisLegalTime(DateTimedt,stringtime_intervals)
{
//当前时间
inttime_now=dt.Hour*10000+dt.Minute*100+dt.Second;
//查看各个时间区间
string[]time_interval=time_intervals.Split(';');
foreach(stringtimeintime_interval)
{
//空数据直接跳过
if(string.IsNullOrWhiteSpace(time))
{
continue;
}
//一段时间格式:六个数字-六个数字
if(!Regex.IsMatch(time,"^[0-9]{6}-[0-9]{6}$"))
{
Console.WriteLine("{0}:错误的时间数据",time);
}
stringtimea=time.Substring(0,6);
stringtimeb=time.Substring(7,6);
inttime_a,time_b;
//尝试转化为整数
if(!int.TryParse(timea,outtime_a))
{
Console.WriteLine("{0}:转化为整数失败",timea);
}
if(!int.TryParse(timeb,outtime_b))
{
Console.WriteLine("{0}:转化为整数失败",timeb);
}
//如果当前时间不小于初始时间,不大于结束时间,返回true
if(time_a<=time_now&&time_now<=time_b)
{
returntrue;
}
}
//不在任何一个区间范围内,返回false
returnfalse;
}
}
}
当前时间为2015年8月15日16:21:31,故程序输出为False
希望本文所述对大家的C#程序设计有所帮助。
