C#次匹配
我用C#写了一个小函数,这不是我的主要语言,所以对我来说有点陌生C#次匹配,c#,date,time,string-matching,C#,Date,Time,String Matching,我用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 == strTheT
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(strketime==strtime)
需要
如果(strketime==stretime+或-5分钟)
我的问题是匹配时间,因为它们是字符串,可能先将键(原始时间)转换回日期,然后再执行此操作,但我对c#非常陌生。要将发送的字符串转换为等效的日期时间值,请使用以下代码:
var keyDateTime = Convert.ToDateTime(strKeyTime);
var strTheTime = DateTime.Now
在此,您可以使用此值与原始时间值进行比较,如下所示:
if (keyDateTime == strTheTime || (keyDateTime > strTheTime && keyDateTime < strTheTime.AddMinutes(5))
{
return true;
}
if(keyDateTime==strtime | |(keyDateTime>strtime&&keyDateTime
前面的代码块将首先检查我们是否得到了精确匹配,或者发送到该方法的时间是否在原始时间和额外5分钟的时间偏移之间
就这样,如果这不是你需要的,请告诉我,以便我可以为你更新我的答案,谢谢
--如果我的答案正确,请不要忘记“标记为答案”。要将发送的字符串转换为等效的日期时间值,请使用以下代码:
var keyDateTime = Convert.ToDateTime(strKeyTime);
var strTheTime = DateTime.Now
在此,您可以使用此值与原始时间值进行比较,如下所示:
if (keyDateTime == strTheTime || (keyDateTime > strTheTime && keyDateTime < strTheTime.AddMinutes(5))
{
return true;
}
if(keyDateTime==strtime | |(keyDateTime>strtime&&keyDateTime
前面的代码块将首先检查我们是否得到了精确匹配,或者发送到该方法的时间是否在原始时间和额外5分钟的时间偏移之间
就这样,如果这不是你需要的,请告诉我,以便我可以为你更新我的答案,谢谢
--如果我的答案正确,请不要忘记“标记为答案”。如果您将它们都转换(或保留)为日期时间,则可以使用:
TimeSpan delta=dateTime1-dateTime2;
if(Math.Abs(delta.TotalMinutes)如果将它们都转换(或保留)为日期时间,则可以使用:
TimeSpan delta=dateTime1-dateTime2;
如果(Math.Abs(delta.TotalMinutes)“可能先将键(原始时间)转换回日期,然后再执行”听起来像是一个合理的解决方案。我会这样做:
- 将这两个字符串转换为DateTime实例
- 使用
DateTime.Subtract(DateTime值)
()
- 检查TimeSpanInstance.TotalMinutes是否小于或等于5
第一步是,如果没有关于字符串格式的信息,我真的不能给你任何建议。但是,一旦完成了,剩下的应该很简单。“也许先将密钥(原始时间)转换回日期,然后再执行”听起来像是一个合理的解决方案。我会这样做:
- 将这两个字符串转换为DateTime实例
- 使用
DateTime.Subtract(DateTime值)
()
- 检查TimeSpanInstance.TotalMinutes是否小于或等于5
第一步是,如果没有关于字符串格式的信息,我真的不能给你任何建议。但是,一旦完成了,剩下的应该很简单。return-strKeyTime==strtetime;
return-strKeyTime==strteime;