简体   繁体   English

如何查找当前时间是否在C#中的时间范围内

[英]How can I find if current time fall in time range in c#

I am new to c# and I am using windows forms. 我是C#的新手,正在使用Windows窗体。

Any one knows how can I find if the current time fall in time range in c#. 任何人都知道如何找到当前时间是否在c#的时间范围内。

For example: I want to check if the current time is between 12am and 4am. 例如:我想检查当前时间是否在12am和4am之间。

I tried the following code but it gives me true statement when the current time is 6pm which is incorrect: 我尝试了以下代码,但是当当前时间是6pm时,它给出了正确的语句,这是不正确的:

 if (DateTime.Now >= DateTime.Today.AddHours(0) && 
     DateTime.Now <= DateTime.Today.AddHours(4))
 {
     MessageBox.Show("time is between 12am and 4am");
 }

Please help me. 请帮我。 thank you 谢谢

  TimeSpan start = new TimeSpan(00, 0, 0); //12  o'clock am
  TimeSpan end = new TimeSpan(04, 0, 0); //4 o'clock am
  TimeSpan now = DateTime.Now.TimeOfDay;
  if ((now > start) && (now < end))
  {
     MessageBox.Show("time is between 12am and 4am");
   }
if(DateTime.Now.Hour >= 0 & DateTime.Now.Hour < 4)

just tested 刚刚测试

Debug.WriteLine(DateTime.Now.Hour);
if(DateTime.Now.Hour >= 0 & DateTime.Now.Hour < 4)
    Debug.WriteLine("in");
else
    Debug.WriteLine("out");

DateTime.Compare takes in two datetimes and compares them. DateTime.Compare接受两个日期时间并进行比较。 If the first is after or later than the second it returns 1; 如果第一个在第二个之后或之后,则返回1;否则,返回1。 if it's earlier than the second it returns -1. 如果早于第二个,则返回-1。 Otherwise it returns 0 否则返回0

if (DateTime.Compare(DateTime.Now, DateTime.Today.AddHours(0)) > 0  && DateTime.Compare(DateTime.Now, DateTime.Today.AddHours(4)) < 0)
{
    MessageBox.Show("time is between 12am and 4am");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM