首 页最新软件下载排行文章资讯投稿发布下载专题
维维下载站
您的位置:首页编程开发网络编程编程其它 → C#怎么判断一个时间点是否位于给定时间区间例子

C#怎么判断一个时间点是否位于给定时间区间例子

来源:维维整理 发布时间:2015-8-18 14:33:06 人气:

C#怎么判断一个时间点是否位于给定时间区间实现方法,本实例讲述了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

相关下载
栏目导航
本类热门阅览