Archive for October, 2010

How to get the week number for a date in C#

Today I needed to know which week of the year a certain day was in. My first instinct was DateTime.Now.Week but it seems there is no Week property on a DateTime instance. So I started looking for a way to get the week number. As it turns out the CultureInfo class will get you where you want to go using the Calendar property.

I updated my extensions library (How to get the mime type of a file using the name of a file in C# and PART 2: How to get the mime type of a file using the name of a file in C# ) to add an extension method called WeekNumber for a DateTime instance here is the code:


    public static class DateTimeExtensions
    {
        public static int WeekNumber(this System.DateTime value)
        {
            return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(value, CalendarWeekRule.FirstFourDayWeek,
                                                                     DayOfWeek.Monday);

        }
    }

You can download my updated extension library here : Suddenelfilio.ExtensionMethods.zip
Downloaded 204 times

, , , ,

No Comments