Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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#.

like image 218
McAzzaMan Avatar asked May 05 '11 05:05

McAzzaMan


People also ask

How do you calculate the number of weeks between two dates?

To determine how many weeks elapsed between two dates, we can use a simple formula to find the number of days between the dates, then divide by 7. The formula will return a decimal number.

How do I calculate number of weeks between 2 dates in Excel?

To find out how many weeks there are between two dates, you can use the DATEDIF function with "D" unit to return the difference in days, and then divide the result by 7. Where A2 is the start date and B2 is the end date of the period you are calculating.

How do you calculate remaining weeks in Java?

Now we can use the ChronoUnit enum to calculate elapsed weeks. long weeks = ChronoUnit. WEEKS. between( startZdt , stopZdt );


2 Answers

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.

like image 159
Oded Avatar answered Sep 24 '22 03:09

Oded


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.

like image 38
V4Vendetta Avatar answered Sep 23 '22 03:09

V4Vendetta