[英]How to check, is “X minutes” passed with timeStamp in C#?
I am trying to create script that checks is the current time passed, but getting some errors. 我正在尝试创建检查当前时间的脚本,但是会出现一些错误。
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
TimeSpan compare = currentTime + pauseMin;
if (currentTime >= compare)
return null;
You can't compare DateTime and TimeSpan. 您无法比较DateTime和TimeSpan。
Try var compare = currentTime.AddMinutes(1)
尝试var compare = currentTime.AddMinutes(1)
If you need to somehow use TimeSpan, use Jamie F's answer. 如果您需要使用TimeSpan,请使用Jamie F的答案。
I would write this as 我会这样写
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
DateTime compare = currentTime.Add(pauseMin);
if (currentTime >= compare) {
return null;
}
This uses the type of object that you are trying to represent with everything. 这将使用您要代表的所有对象的类型。 DateTime's can have Timespan's added to them: https://msdn.microsoft.com/en-us/library/system.datetime.add%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 DateTime可以添加Timespan: https ://msdn.microsoft.com/en-us/library/system.datetime.add%28v=vs.110%29.aspx?f = 255&MSPPError = -2147217396
Or Istern's answer if you are always just adding an integer of minutes to the time. 或者,如果您始终只是将整数分钟添加到时间,则可以使用Istern的答案。
DateTime
and TimeSpan
is different. DateTime
和TimeSpan
是不同的。 You can use currentTime
like this: 您可以像这样使用currentTime
:
TimeSpan currentTime = TimeSpan.FromTicks(DateTime.Now.Ticks);
And you can get passed minutes like this: 您可以像这样通过分钟:
double minutes = (compare - currentTime).TotalMinutes;
If you just want to pause for 1 minute, you can use 如果您只想暂停1分钟,可以使用
System.Threading.Thread.Sleep(1000 * 60); // 1 minute = 60000 milliseconds
If you want your function to run for 1 minute, you can use something like 如果您希望函数运行1分钟,可以使用类似
var returnAt = DateTime.Now().AddMinutes(1);
while ( true )
{
// your code here ?
if ( DateTime.Now() >= returnAt ) return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.