C# 判断一个时间点是否位于给定的时间区间(字符串格式)

本文中实现了函数

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&gt53B
        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

猜你喜欢

转载自blog.csdn.net/xzw18287443015/article/details/50253875