Q:

Week difference between 2 dates in C#

I'm trying to make a function in C# that returns the week difference between two dates. Its goal is to provide the same result of:
select datediff(ww,'2018-04-13','2018-04-16') as diff

In the example above there is only 3 days between these dates, but they are in different weeks, so the result should be 1.
I've tried to use .TotalDays but it's not working properly. I also tried .GetWeekOfYear but it won't return correctly when the year of the dates are different. I've seem many questions here on StackOverflow and on other forums and so far none of them match my case.  This is the function I'm trying to far:
public static int GetWeekDiff(DateTime dtStart, DateTime dtEnd) {
    // Doesn't work
    var val = ((dtEnd - dtStart).TotalDays / 7);
    val = Math.Ceiling(val);
    return Convert.ToInt32(val);

    // Doesn't work well between years
    DateTimeFormatInfo dinfo = DateTimeFormatInfo.CurrentInfo;
    var x = dinfo.Calendar.GetWeekOfYear(dtStart, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
    var y = dinfo.Calendar.GetWeekOfYear(dtEnd, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);

    return y - x;

}

In the first part of my function, I tried what is described in this post. It didn't work
Can you help me? 
Thanks in advance.

A:

First figure how many days there are between the two dates. Divide the number of days by 7 to get full weeks. 
Now figure out if there's an extra week to be counted by finding taking the number of days modulus 7 to get any remaining days. If the first date plus remaining days falls in a different week, add an extra week on to the count.
void Main()
{

    var first = new DateTime(2018, 04, 13);
    var second = new DateTime(2018, 04, 16);

    Console.WriteLine(weekDiff(first, second));
}

public int weekDiff(DateTime d1, DateTime d2, DayOfWeek startOfWeek = DayOfWeek.Monday)
{
    var diff = d2.Subtract(d1);

    var weeks = (int)diff.Days / 7;

    // need to check if there's an extra week to count
    var remainingDays = diff.Days % 7;
    var cal = CultureInfo.InvariantCulture.Calendar;
    var d1WeekNo = cal.GetWeekOfYear(d1, CalendarWeekRule.FirstFullWeek, startOfWeek);
    var d1PlusRemainingWeekNo = cal.GetWeekOfYear(d1.AddDays(remainingDays), CalendarWeekRule.FirstFullWeek, startOfWeek);

    if (d1WeekNo != d1PlusRemainingWeekNo)
        weeks++;

    return weeks;
}

