C#實現(xiàn)判斷一個時間點是否位于給定時間區(qū)間的方法
本文實例講述了C#實現(xiàn)判斷一個時間點是否位于給定時間區(qū)間的方法。分享給大家供大家參考。具體如下:
本文中實現(xiàn)了函數(shù)
給定一個字符串表示的時間區(qū)間time_intervals:
1)每個時間點用六位數(shù)字表示:如12點34分56秒為123456
2)每兩個時間點構(gòu)成一個時間區(qū)間,中間用字符'-'連接
3)可以有多個時間區(qū)間,不同時間區(qū)間間用字符';'隔開
例如:"000000-002559;030000-032559;060000-062559;151500-152059"
若DateTime類型數(shù)據(jù)dt所表示的時間在字符串time_intervals中,
則函數(shù)返回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>
/// 判斷一個時間是否位于指定的時間段內(nèi)
/// </summary>
/// <param name="time_interval">時間區(qū)間字符串</param>
/// <returns></returns>
static bool isLegalTime(DateTime dt, string time_intervals)
{
//當前時間
int time_now = dt.Hour * 10000 + dt.Minute * 100 + dt.Second;
//查看各個時間區(qū)間
string[] time_interval = time_intervals.Split(';');
foreach (string time in time_interval)
{
//空數(shù)據(jù)直接跳過
if (string.IsNullOrWhiteSpace(time))
{
continue;
}
//一段時間格式:六個數(shù)字-六個數(shù)字
if (!Regex.IsMatch(time, "^[0-9]{6}-[0-9]{6}$"))
{
Console.WriteLine("{0}: 錯誤的時間數(shù)據(jù)", time);
}
string timea = time.Substring(0, 6);
string timeb = time.Substring(7, 6);
int time_a, time_b;
//嘗試轉(zhuǎn)化為整數(shù)
if (!int.TryParse(timea, out time_a))
{
Console.WriteLine("{0}: 轉(zhuǎn)化為整數(shù)失敗", timea);
}
if (!int.TryParse(timeb, out time_b))
{
Console.WriteLine("{0}: 轉(zhuǎn)化為整數(shù)失敗", timeb);
}
//如果當前時間不小于初始時間,不大于結(jié)束時間,返回true
if (time_a <= time_now && time_now <= time_b)
{
return true;
}
}
//不在任何一個區(qū)間范圍內(nèi),返回false
return false;
}
}
}
當前時間為2015年8月15日 16:21:31,故程序輸出為False
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
使用checked語句防止數(shù)據(jù)溢出的解決方法
本篇文章是對用checked語句防止數(shù)據(jù)溢出的解決方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
WPF使用DrawingContext實現(xiàn)二維繪圖
這篇文章介紹了WPF使用DrawingContext實現(xiàn)二維繪圖的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06
C#使用DataSet Datatable更新數(shù)據(jù)庫的三種實現(xiàn)方法
這篇文章主要介紹了C#使用DataSet Datatable更新數(shù)據(jù)庫的三種實現(xiàn)方法,需要的朋友可以參考下2014-08-08

