C#完成斷定一個時光點能否位於給准時間區間的辦法。本站提示廣大學習愛好者:(C#完成斷定一個時光點能否位於給准時間區間的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是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
願望本文所述對年夜家的C#法式設計有所贊助。