Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

c# - How can I calculate/find the week-number of a given date?

How can I calculate/find the week-number of a given date?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var currentCulture = CultureInfo.CurrentCulture;
var weekNo = currentCulture.Calendar.GetWeekOfYear(
                new DateTime(2013, 12, 31),
                currentCulture.DateTimeFormat.CalendarWeekRule,
                currentCulture.DateTimeFormat.FirstDayOfWeek);

Be aware that this is not ISO 8601 compatible. In Sweden we use ISO 8601 week numbers but even though the culture is set to "sv-SE", CalendarWeekRule is FirstFourDayWeek, and FirstDayOfWeek is Monday the weekNo variable will be set to 53 instead of the correct 1 in the above code.

I have only tried this with Swedish settings but I'm pretty sure that all countries (Austria, Germany, Switzerland and more) using ISO 8601 week numbers will be affected by this problem.

Peter van Ooijen and Shawn Steele has different solutions to this problem.

Here's a compact solution

private static int WeekOfYearISO8601(DateTime date)
{
    var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);
    return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

It's been tested for the following dates

var datesAndISO8601Weeks = new Dictionary<DateTime, int>
                        {
                            {new DateTime(2000, 12, 31), 52},
                            {new DateTime(2001, 1, 1), 1},
                            {new DateTime(2005, 1, 1), 53},
                            {new DateTime(2007, 12, 31), 1},
                            {new DateTime(2008, 12, 29), 1},
                            {new DateTime(2010, 1, 3), 53},
                            {new DateTime(2011, 12, 31), 52},
                            {new DateTime(2012, 1, 1), 52},
                            {new DateTime(2013, 1, 2), 1},
                            {new DateTime(2013, 12, 31), 1},
                        };

foreach (var dateWeek in datesAndISO8601Weeks)
{
    Debug.Assert(WeekOfYearISO8601(dateWeek.Key) == dateWeek.Value, dateWeek.Key.ToShortDateString() + " should be week number " + dateWeek.Value + " but was " + WeekOfYearISO8601(dateWeek.Key));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...