开发者

Most efficient way to count number of weeks between two datetimes [closed]

开发者 https://www.devze.com 2023-03-03 15:34 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form.开发者_C百科 Fo
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form.开发者_C百科 For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

Exactly as it says on the tin, I just need the most efficient way of counting weeks (i.e. 7-day spans, not calendar weeks) between two dates in C#.


Get the number of days and divide by 7.

int weeks = (date1 - date2).TotalDays / 7;

You may well have a remainder of up to 6 days that will not be included in the number of weeks.


I assume you want to get this on the basis of the Calender. For this you need System.Globalization

DateTime date1 = DateTime.Now;
DateTimeFormatInfo dinfo = DateTimeFormatInfo.CurrentInfo;
dinfo.Calendar.GetWeekOfYear(date1, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday)

Based on your need you have to set the Calender week rule and the first day of the week.

This gives you a week number for the calender. you can get the same for your other date, the difference is your weeks count

Hope this helps you.


Try this to get the number of days:

TimeSpan ts = date1.Subtract(date2);
int dateDiff = ts.Days();

Then, like @Oded said, divide by 7

int totalWeeks = (int) dateDiff / 7;

Cheers!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号