Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get or convert Week of year to ISO week

Tags:

vb.net

While trying to get the number of weeks in a year I tried this:

maxWeek = calendar.GetWeekOfYear(New Date(t_year, 12, 31), 
          CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

Which didn't work well for my purpouse, but I noticed something weird. For 2014-12-31 it returned 53 and for 2015-01-01 it returned 1. For 2015-01-05 it returned 2. That means that the weeks 53 and 1 are smaller then 7 days!

I need the result to be ISO Week compliant. I couldn't find online any examples of calendars following this same logic. Them all show the week 1 as from 2014-12-29 to 2015-01-04.

like image 460
mathiasfk Avatar asked Mar 17 '23 11:03

mathiasfk


1 Answers

Your original post does not mention you are looking for ISO week, which may have made what you want unclear.

The NET GetWeekOfYear using FirstFourDayWeek and DayOfWeek.Monday is almost like an ISO Week. The difference is that an ISO Week is always seven days. Keep in mind that an ISO Date is not just a different format, but a different calendar complete with its own terms (like leap week). Your default NET calandar on the other hand is Gregorian.

It is not hard to tweak a NET WOY to an ISO Week:

Public Shared Function GetISOWeekOfYear(dt As DateTime) As Integer
    Dim cal As Calendar = CultureInfo.InvariantCulture.Calendar
    Dim d As DayOfWeek = cal.GetDayOfWeek(dt)

    If (d >= DayOfWeek.Monday) AndAlso (d <= DayOfWeek.Wednesday) Then
        dt = dt.AddDays(3)
    End If

    Return cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

End Function

Simple tester for 12/31/xxxx:

For n As Integer = 1990 To 2016
    Console.WriteLine("{0}: week:{1}", n.ToString,
                      GetISOWeekOfYear(New DateTime(n, 12, 31)).ToString)
Next

Output of just the last few:

2005: week:52
2006: week:52
2007: week:1
2008: week:1
2009: week:53
2010: week:52
2011: week:52
2012: week:1
2013: week:1
2014: week:1
2015: week:53
2016: week:52

like image 50
Ňɏssa Pøngjǣrdenlarp Avatar answered Mar 24 '23 12:03

Ňɏssa Pøngjǣrdenlarp