Q:

Get number of ISO weeks in given year in C#

I'm trying to get the number of ISO weeks in given year/leap year. I saw that .Net Core 3.0 have ISOWeek.GetWeeksInYear class, but we're running .Net Core 2.2.1... and it's not possible to update at the moment...
I've tried this:
var cultInfo = CultureInfo.CurrentCulture;
var lastDayOfYear = new DateTime(2019, 12, 31);
var numberOfWeeks = cultInfo.Calendar.GetWeekOfYear(
                                    lastDayOfYear,
                                    cultInfo.DateTimeFormat.CalendarWeekRule,
                                    DayOfWeek.Monday);

With 2019 it returns 53, it's not correct by the result I wanted (52). And if I change the date to 2020 it is 53, which is correct, but yeah, not by ISO which is what I want.
Thanks in advance.

A:

You can have a look at ISOWeek sources and implement this method by yourself (since you can't target .NET Core 3.x)
private const int WeeksInLongYear = 53;
private const int WeeksInShortYear = 52;

public static int GetWeeksInYear(int year)
{
    if (year < 1 || year > 9999)
    {
        throw new ArgumentOutOfRangeException(nameof(year));
    }

    static int P(int y) => (y + (y / 4) - (y / 100) + (y / 400)) % 7;

    if (P(year) == 4 || P(year - 1) == 3)
    {
        return WeeksInLongYear;
    }

    return WeeksInShortYear;
}

Then use it
var weeks = GetWeeksInYear(2019); //returns 52
weeks = GetWeeksInYear(2020); //returns 53

Please, keep in mind, that static local functions are supported starting from C# 8, so you should switch to this version or rewrite a code a little bit

