判断时间是否在某个时间段内 1 using System; 2 3 namespace TimeEval 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Console.WriteLine("Hello World!"); 10 11 Console.WriteLine("======================="); 12 13 bool oneRet = IsInTimeRange(DateTime.Now, "1:00", "8:00"); 14 Console.WriteLine("后夜- - - -当前时间:{0},范围:1:00-8:00,结果:{1}", DateTime.Now, oneRet); 15 16 bool twoRet = IsInTimeRange(DateTime.Now, "8:00", "17:00"); 17 Console.WriteLine("白班- - - -当前时间:{0},范围:8:00-17:00,结果:{1}", DateTime.Now, twoRet); 18 19 bool threeRet = IsInTimeRange(DateTime.Now, "17:00", "1:00"); 20 Console.WriteLine("前夜- - - -当前时间:{0},范围:17:00-1:00,结果:{1}", DateTime.Now, threeRet); 21 22 Console.ReadKey(); 23 } 24 /// <summary> 25 /// 判断时间是否在某个时间段内 26 /// </summary> 27 /// <param name="nowTime"></param> 28 /// <param name="beginHm"></param> 29 /// <param name="endHm"></param> 30 /// <returns></returns> 31 public static bool IsInTimeRange(DateTime nowTime, string beginHm, string endHm) 32 { 33 DateTime start = DateTime.Parse(beginHm); 34 DateTime end = DateTime.Parse(endHm); 35 if (start.CompareTo(end) == 1 || start.Equals(end)) 36 { 37 if (GetTimeSpan(nowTime.ToString()) >= GetTimeSpan(start.ToString()) || GetTimeSpan(nowTime.ToString()) <= GetTimeSpan(end.ToString())) 38 { 39 return true; 40 } 41 } 42 else 43 { 44 if (GetTimeSpan(nowTime.ToString()) >= GetTimeSpan(start.ToString()) && GetTimeSpan(nowTime.ToString()) <= GetTimeSpan(end.ToString())) 45 { 46 return true; 47 } 48 } 49 return false; 50 } 51 52 /// <summary> 53 /// 获取类似java gettime() 格式的时间 54 /// </summary> 55 /// <param name="time">要转换的时间</param> 56 /// <returns>long类型的时间秒数</returns> 57 public static long GetTimeSpan(string time) 58 { 59 if (string.IsNullOrEmpty(time)) 60 { 61 TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间 62 return (long)ts.TotalMilliseconds; //精确到毫秒 63 } 64 else 65 { 66 DateTime dt = Convert.ToDateTime(time); 67 TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间 68 return (long)ts.TotalMilliseconds; //精确到毫秒 69 } 70 } 71 } 72 }
原文地址:https://www.cnblogs.com/yumaster/p/12096771.html
时间: 2024-11-07 14:49:11