15,964,238 members
1.00/5 (1 vote)
See more:
Hi,

I have the two date's such as From Date and To Date.

When i take a count of week for the Two Date's it showing empty.

From Date : 12/1/2011
To Date : 12/22/2011

Difference Count of week is : 3 ( But, it's showing wrong).

What is the problem here..

see my code...
-----------

C#
```If txtStartdate.Text <> "" And txtEndDate.Text <> "" Then
Dim WeeksDiff As Integer
Dim monthsApart As Integer = 12 * (StDate.Year - EdDate.Year) + StDate.Month - EdDate.Month
WeeksDiff = Math.Abs(monthsApart * 4)
txtDuration.Text = WeeksDiff
End If
```
Posted
Updated 12-Dec-11 0:41am
v2

Solution 5

The other solutions should give you what you need to get the answer you expect. The problem with your code (a question you asked) is obvious if you manually perform the calculations for your example. Since StDate.Year = EndDate.Year and StDate.Month = EndDate.Month for your two dates, (12/1/2011 and 12/22/2011), you have monthsApart= 12 x 0 + 0 = 0. Then WeeksDiff = 0 * 4 = 0. I assume your comment that the answer shows empty actually means the answer is 0.

If test cases don't return the expected result check both the coding and the algorithm.

Solution 3

The major problem is that there aren't 4 weeks in a month: there are 28/7, 29/7, 30/7, or 31/7. Only one of which is 4.

Try this:
VB
```Public Shared Function NumberOfWeeks(dateFrom As DateTime, dateTo As DateTime) As Integer
Dim diff As TimeSpan = dateTo.Subtract(dateFrom)

If diff.Days <= 7 Then
If dateFrom.DayOfWeek > dateTo.DayOfWeek Then
Return 2
End If
Return 1
End If

Dim Days As Integer = diff.Days - 7 + CInt(dateFrom.DayOfWeek)
Dim WeekCount As Integer = 1
Dim DayCount As Integer = 0
WeekCount = 1
While DayCount < Days
DayCount += 7
WeekCount += 1
End While

Return WeekCount
End Function```

Valery Possoz 12-Dec-11 6:46am
A very good and detailed answer! it's a 5 :)

Solution 4

Hello,

I would do that differently:

VB
```Dim strFromDate, strToDate As String

strFromDate = "12/1/2011"
strToDate = "12/22/2011"

Dim toDate, fromDate As DateTime
toDate = DateTime.Parse(strToDate, New CultureInfo("en-US", False))
fromDate = DateTime.Parse(strFromDate, New CultureInfo("en-US", False))

Dim nbWeeks As Long
nbWeeks = Math.Abs(DateDiff(DateInterval.Day, fromDate, toDate) / 7)```

Valery.

Valery Possoz 12-Dec-11 6:44am
By the time I posted my answer 3 other answers were posted! :)

Solution 2

Another method would be to take number of days difference between two dates and divide it by 7.

Solution 6

hi,
You can get by using this query also ...

SQL
`SELECT DATEDIFF( week,'12/1/2011','12/22/2011') as[No of Weeks]`

Regards,
Pal