it is possible with C # test whether the DateTime " 01/29/2016 16:22:00 " is included in the next 24 hours? I have a date that is " 01/28/2016 15:30 " ( DateTime.Now ) and I 'd like to know if it is within the range going forward 24 hours. I hope I explained .
Asked
Active
Viewed 4,546 times
-1
-
3You want to know if `DateTime.Now` is within the next 24 hours? – Tim Schmelter Jan 28 '16 at 15:26
2 Answers
6
(yourDatetime - DateTime.Now) <= TimeSpan.FromHours(24)

M.kazem Akhgary
- 18,645
- 8
- 57
- 118
-
-
It will not work if the `yourDatetime = DateTime.Now.AddHours(-26)`; You can use `Math.Abs`. – Farhad Jabiyev Jan 28 '16 at 15:43
4
You can use AddHours
:
var myDateTime = ...
var now = DateTime.Now;
if (myDateTime <= now.AddHours(24)
&& myDateTime >= now.AddHours(-24))
{
}
Also keep in mind that DateTime
is immutable and they cannot be modified after creation. That is why AddHours
returns a new instance.
Update: After seeing M.kazem's answer I have though that you can also use that:
Math.Abs(myDateTime.Subtract(DateTime.Now).TotalHours) <= 24

Farhad Jabiyev
- 26,014
- 8
- 72
- 98
-
-
@Mr.Developer Glad to help. Also, updated my answer. You can use second one also. – Farhad Jabiyev Jan 28 '16 at 15:44
-