问题
I tried this code on three different machines and I keep getting 28 for today's week number:
Dim myCI As New CultureInfo("en-US")
Dim myCal As System.Globalization.Calendar = myCI.Calendar
Dim myCWR As CalendarWeekRule = myCI.DateTimeFormat.CalendarWeekRule
Dim myFirstDOW As DayOfWeek = myCI.DateTimeFormat.FirstDayOfWeek
Dim week As Integer = myCal.GetWeekOfYear(DateTime.Now, myCWR, myFirstDOW)
It should return 27. Why do I get 28?
回答1:
On my machine, I get the following values for the en-US culture:
myCWR = FirstDay
myFirstDOW = Sunday
week = 28 (with DateTime.Today = July 7, 2016)
This is correct. By passing CalendarWeekRule.FirstDay and DayOfWeek.Sunday to Calendar.GetWeekOfYear, you're telling the method that you want week 2 to start on the first Sunday after January 1 (which was January 3, 2016). So week 1 only has two days.
If you want week 2 to start on January 8 regardless of the day of the week that it falls on, then you must pass the day of week of January 8 (or equivalently, January 1) to GetWeekOfYear:
Dim myFirstDOW As DayOfWeek = New DateTime(DateTime.Now.Year, 1, 1).DayOfWeek
Dim week As Integer = myCal.GetWeekOfYear(DateTime.Now, myCWR, myFirstDOW)
This sets week
to 27.
来源:https://stackoverflow.com/questions/38258118/getweekofyear-returns-the-wrong-week-number