[英]How to check, is “X minutes” passed with timeStamp in C#?
我正在尝试创建检查当前时间的脚本,但是会出现一些错误。
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
TimeSpan compare = currentTime + pauseMin;
if (currentTime >= compare)
return null;
您无法比较DateTime和TimeSpan。
尝试var compare = currentTime.AddMinutes(1)
如果您需要使用TimeSpan,请使用Jamie F的答案。
我会这样写
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
DateTime compare = currentTime.Add(pauseMin);
if (currentTime >= compare) {
return null;
}
这将使用您要代表的所有对象的类型。 DateTime可以添加Timespan: https ://msdn.microsoft.com/en-us/library/system.datetime.add%28v=vs.110%29.aspx?f = 255&MSPPError = -2147217396
或者,如果您始终只是将整数分钟添加到时间,则可以使用Istern的答案。
DateTime
和TimeSpan
是不同的。 您可以像这样使用currentTime
:
TimeSpan currentTime = TimeSpan.FromTicks(DateTime.Now.Ticks);
您可以像这样通过分钟:
double minutes = (compare - currentTime).TotalMinutes;
如果您只想暂停1分钟,可以使用
System.Threading.Thread.Sleep(1000 * 60); // 1 minute = 60000 milliseconds
如果您希望函数运行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.