Reputation: 11
I wanted to find if two DateTime
are within a week.
One of them is the current system Datetime
, which I got it by using:
DateTime CurrentDateTime = new DateTime();
CurrentDateTime = DateTime.Now;
The other DateTime
will just be a selected date. Assuming it is stored in a variable called : ExportDate
.
So, I can find the difference between them by doing
ExportDate.Subtract(CurrentDateTime)
But I cannot change this value into a int for comparing...
So how should I compare this to DateTime
to see if this two dates are greater then 0Days, and less then 7Days.
Upvotes: 1
Views: 615
Reputation: 498
This is how you do it in PHP
function isTwoDatesWithinTheSameWeek($date1, $date2){
$d1 = strtotime($date1); //"2015-01-01"
$d2 = strtotime($date2); //"2016-01-05"
$d1w = date("W", $d1);
$d2w = date("W", $d2);
return $d1w === $d2w;
}
Upvotes: 0
Reputation: 703
You can simply use the DayOfYear property of DateTime to get the day in the year and then check if the difference is less than 7 or not. You can try:
bool isWithinAWeek = Math.Abs(currentDateTime.DayOfYear-exportDate.DayOfYear)>7?false:true;
Upvotes: 0
Reputation: 14007
Try to compare the TotalDays
of the resulting TimeSpan
. Depending on which is later, the result must be between -7 and 7. Use Math.Abs
to avoid comparing the value against both bounds:
bool isWithinWeek = Math.Abs(ExportDate - CurrentDate).TotalDays) < 7
If the time of day is irrelevant, compare only the dates:
bool isWithinWeek = Math.Abs(ExportDate.Date - CurrentDate.Date).TotalDays) < 7
Upvotes: 1
Reputation:
Subtracting two datetimes gives you a TimeSpan. This class comes with a property called TotalDays.
Gets the value of the current TimeSpan structure expressed in whole and fractional days.
Src: https://msdn.microsoft.com/en-Us/library/system.timespan(v=vs.110).aspx
You can use to count the number of days I guess.
Regards, Seb
Upvotes: 1