Kenneth Montealto Kenneth Montealto - 2 months ago 8
C# Question

How Can I determine "weeks" using DateTime

I have a start date column called

StartDate
in a database table. I need to determine how many weeks elapsed from the start date until today.

Here is my code:

DateTime startDate = new DateTime(StartedDate);
if (startDate.addDays(7) == DateTime.Today) {
// One week elapsed.
}


Let's say
startDate
is 9/29/2016. If I add 7 days, the total becomes 10/7/2016.
If, for example, today is 10/7/2016 - the same date as above, so there is 1 week from the start date. How can I determine the number of weeks for dates in the future?

Answer

Try

if(DateTime.Now.Subtract(StartDate).TotalDays%7==0)

This will give you the modulus of days and equal 0 every 7 days. It will, however, be time sensistve (if StartDate is 2:00PM, days will be 6 until 2:00PM on day 7). If you are only concerned about the day (not time after midnight) use:

 if(DateTime.Now.Date.Subtract(StartDate.Date).TotalDays%7==0)
Comments