Languages
[Edit]
EN

C# / .NET - get number of weeks in year

12 points
Created by:
JustMike
3491

In C# / .NET it is possible to get number of weeks in following way.

Number of weeks example

public static class TimeUtils
{
	public static int GetNumberOfWeeks(int year, CultureInfo culture = null)
	{
		if (culture == null)
			culture = CultureInfo.InvariantCulture;

		DateTime time = new DateTime(year, 12, 31);
		DateTimeFormatInfo format = culture.DateTimeFormat;

		return culture.Calendar.GetWeekOfYear(time, 
			format.CalendarWeekRule, format.FirstDayOfWeek);
	}
}

Example:

for(int year = 2000; year < 2030; ++year)
{
	int numberOfWeeks = TimeUtils.GetNumberOfWeeks(year);

	Console.WriteLine(year + " has " + numberOfWeeks + " weeks");
}

Output:

2000 has 54 weeks
2001 has 53 weeks
2002 has 53 weeks
2003 has 53 weeks
2004 has 53 weeks
2005 has 53 weeks
2006 has 53 weeks
2007 has 53 weeks
2008 has 53 weeks
2009 has 53 weeks
2010 has 53 weeks
2011 has 53 weeks
2012 has 53 weeks
2013 has 53 weeks
2014 has 53 weeks
2015 has 53 weeks
2016 has 53 weeks
2017 has 53 weeks
2018 has 53 weeks
2019 has 53 weeks
2020 has 53 weeks
2021 has 53 weeks
2022 has 53 weeks
2023 has 53 weeks
2024 has 53 weeks
2025 has 53 weeks
2026 has 53 weeks
2027 has 53 weeks
2028 has 54 weeks
2029 has 53 weeks
Note: above example returns different number of weeks depending of Calendar.GetWeekOfYear method configuration.

References

  1. Calendar.GetWeekOfYear Method - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.