How can I determine the week number of a certain date?

后端 未结 3 2107
小鲜肉
小鲜肉 2020-11-30 11:38

I\'m trying to make a calendar using wpf. By using itemsPanel and more, I have a grid with 7 columns(sunday-saturday) and 6 rows(week# of month). If i can find the starting

3条回答
  •  时光取名叫无心
    2020-11-30 12:06

    You can use Calendar.GetWeekOfYear from Globalization to do this.

    Here's the MSDN docs for it: http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx

    You should pass the appropriate culture properties from CultureInfo.CurrentCulture to GetWeekOfYear so that you match the current culture properly.

    Example:

    int GetWeekOfYear(DateTime date)
    {
        return Calendar.GetWeekOfYear(
            date,
            CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule,
            CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
        );
    }
    

    You could easily modify this into an extension method on DateTime:

    static int GetWeekOfYear(this DateTime date)
    {
        return Calendar.GetWeekOfYear(
            date,
            CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule,
            CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
        );
    }
    

提交回复
热议问题