简体   繁体   English

如何比较Firsttime endTime和当前时间之间的两个Time?

[英]How to compare two Time between Firsttime endTime with current time?

Can any one describe me how compare two given time with current time? 谁能描述我如何比较两个给定时间与当前时间?

I have Start time 11 AM and End time 1PM. 我的开始时间是11 AM,结束时间是1PM。 I have timer to tick only when time hour between 11AM to 1PM every day. 我有计时器仅在每天的上午11点到下午1点之间计时。

I have below code but its not working fine Please check. 我有以下代码,但无法正常工作,请检查。

TimeSpan StartHit = new TimeSpan(11, 0, 0);
TimeSpan EndHit = new TimeSpan(1, 0, 0);
if (DateTime.Now.TimeOfDay >= StartHit && DateTime.Now.TimeOfDay <= EndHit)
{
     //my task here
}

You need to use 13 as an hour, not 1 in your EndHit . 您需要使用13作为小时,而不是EndHit 1

TimeSpan StartHit = new TimeSpan(11, 0, 0);
TimeSpan EndHit = new TimeSpan(13, 0, 0);
if (DateTime.Now.TimeOfDay >= StartHit && DateTime.Now.TimeOfDay <= EndHit)
{
   //my task here
}

TimeOfDay property represents the time interval that has elapsed since midnight . TimeOfDay属性表示自午夜以来经过的时间间隔。 If you use 1 as an hour, it will be 1 AM not 1 PM . 如果您将1用作小时,则将是1 AM而不是1 PM

And of course, a TimeSpan doesn't keep these values as 1 AM or 1 PM , these are just string representation of them. 当然, TimeSpan不会将这些值保留为1 AM1 PM ,它们只是它们的字符串表示形式。 It keeps them as an integer values as 1 and 13 . 它将它们保留为113的整数。

Use 采用

TimeSpan EndHit = new TimeSpan(13, 0, 0);

TimeSpan(1, 0, 0) is for 1 AM TimeSpan(1、0、0)适用于1 AM

this code should be working fine: 这段代码应该可以正常工作:

 DateTime time1 = DateTime.Now;
 DateTime time2 = Convert.ToDateTime("11:00:00 AM");
 DateTime time3 = Convert.ToDateTime("1:00:00 PM");

 if (DateTime.Compare(time1, time3) < 0 && DateTime.Compare(time1, time2) > 0)
 {
 }

For example for DateTime.Compare(time1, time3), if Time1 > time3 it return 1, if time1 < time3 it returns -1 and if time1 = time3 it returns 0. I hope this is helpful. 例如对于DateTime.Compare(time1,time3),如果Time1> time3返回1,如果time1 <time3返回-1,如果time1 = time3返回0。我希望这会有所帮助。

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

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