我试图将DateTime变量与另一个DateTime变量进行比较,如果它们彼此相隔24小时,那么就做一些事情.所以,例如, if (todaysDate == OtherDate) {//do stuff only if otherDate is within 24 hours of todaysDate} 我知道我
if (todaysDate == OtherDate) { //do stuff only if otherDate is within 24 hours of todaysDate }
我知道我可以使用这里的运算符,https://msdn.microsoft.com/en-us/library/ff986512(v=vs.110).aspx来比较日期,但这些比较似乎都没有给我我想要的东西,所以很奇怪这是如何实现的.
使用Subtract方法和TotalHours属性.System.DateTime date1 = new System.DateTime(2018, 4, 24, 22, 15, 0); System.DateTime date2 = new System.DateTime(2018, 4, 24, 13, 2, 0); System.TimeSpan diff1 = date2.Subtract(date1); Console.WriteLine(diff1.TotalHours); if(diff1.TotalHours >= -24 && diff1.TotalHours <=24) { Console.WriteLine("Within +/- 24 Hours"); }