C# 时间匹配
我用 C# 编写了一个小函数,这不是我的主要语言,所以对我来说有点陌生。
public bool CheckForKey(string key)
{
string strKeyTime = Decode(key);
//valid key will be current time +- 5 minutes
string strTheTime = DateTime.Now.ToString("HH:mm:ss tt");
if (strKeyTime == strTheTime)
{
return true;
}
else
{
return false;
}
}
我需要更改此设置以留出 5 分钟时间,所以 if (strKeyTime == strTheTime) 需要是 if (strKeyTime == strTheTime + or - 5 分钟)
我的问题是匹配时间,因为它们是字符串,也许先将键(原始时间)转换回日期,然后再执行,但我对 c# 很陌生
I have written a small function in C# which isn't my main launguage so is coming across a little foreign to me.
public bool CheckForKey(string key)
{
string strKeyTime = Decode(key);
//valid key will be current time +- 5 minutes
string strTheTime = DateTime.Now.ToString("HH:mm:ss tt");
if (strKeyTime == strTheTime)
{
return true;
}
else
{
return false;
}
}
I need to alter this to allow for 5 minutes, so
if (strKeyTime == strTheTime)
needs to be
if (strKeyTime == strTheTime + or - 5 minutes)
my problem is matching the times as they are strings, perhaps convert key(original time) back to a date first and then do it, but I am pretty new to c#
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您将它们都转换(或保留)为 DateTimes,您可以使用 TimeSpan:
研究使用 DateTime.ParseExact (或任何 Parse... 方法)来解析你的 strKeyTime,然后执行与上面类似的操作。
If you convert (or keep) them both to DateTimes you can use TimeSpan:
Look into using the DateTime.ParseExact (or any of the Parse... methods) to parse your strKeyTime, and then do something similar to the above.
要将发送的字符串转换为等效的 DateTime 值,请使用以下代码:
从这里,您可以使用该值与原始时间值进行比较,如下所示:
上一个代码块将首先检查我们是否获得完全匹配,或者发送到该方法的时间介于原始时间和额外 5 分钟的时间偏移之间。
就是这样,如果这不是您需要的,请告诉我,以便我可以为您更新我的答案,谢谢。
-- 如果我的答案是正确的,请不要忘记“标记为答案”。
To convert your sent string to the equivalent DateTime value, use the following code:
from here, you can use this value to compare with your original time value as the following:
the previous block of code will first check if we got an exact match, or the time sent to the method is between the original time and a time shift of additional 5 minutes.
that's it, if this is not what you need, let me know so I may update my answer for you, thanks.
-- if my answer is correct, don't forget to "Mark as answer".
“也许先将密钥(原始时间)转换回日期,然后再执行”听起来像是一个合理的解决方案。我会这样做:
DateTime.Subtract(DateTime value)
存储 TimeSpan 实例中的差异 (http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx )如果没有有关字符串格式化方式的信息,我无法为第一步提供任何建议。然而,一旦完成了这一点,剩下的事情就很容易了。
"perhaps convert key(original time) back to a date first and then do it" sounds like a sound solution. I'd do it this way:
DateTime.Subtract(DateTime value)
( http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx )The first step is something I can't really give you any advice on without information concerning how your string is formatted. However, once this is done, the rest should be easy.