C# 判斷一個時間點是否位於給定的時間區間(字串格式)
阿新 • • 發佈:2018-12-03
本文中實現了函式
static bool isLegalTime(DateTime dt, string time_intervals);
給定一個字5E7��串表示的時間區間time_intervals:
1)每個時間點用六位數字表示:如12點34分56秒為123456
2)每兩個時間點構成一個時間區間,中間用字元’-‘連線
3)可以有多個時間區間,不同時間區間間用字元’;’隔開
例如:”000000-002559;030000-032559;060000-062559;151500-152059”
若DateTime型別資料dt所表示的時間在字串time_intervals中,
則函式5E8��回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)
{
520 Console.WriteLine(isLegalTime(DateTime.Now,
"000000-002559;030000-032559;060000-062559;151500-152059" ));
Console.ReadLine();
}
/// <summary>
/// 判斷一個時間5E6��否位於指定的時間段內
/// </summary>
/// <param name="time_interval">時間區間字串</param>53B
52F// <returns></returns>
static bool isLegalTime(DateTime dt, string time_intervals)
{
//當前時間
int time_now = dt.Hour * 10000 + dt.Minute * 100 + dt.Second;
//檢視各個時間區間
0string[] 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);
}
//如果當前時間不小�58E初始時間,不大於結束時間,返回true
if (time_a <= time_now && time_now <= time_b)
{
return true;
}
}
//不在任何一個區間範圍內,返回false
return false;
}
}
}
當前時間為2014年7月15日 16:21:31,故程式輸出為False
END
感謝原作者!
原文地址:http://my.oschina.net/Tsybius2014/blog/291031