For my project, I need to convert year, week and day of week in DateTime. For this, I use this link : https://github.com/dotnet/runtime/blob/b41f1c5f2fde25d752d857a54c3af24145060cdd/src/libraries/System.Private.CoreLib/src/System/Globalization/ISOWeek.cs#L102-L139
BUT, in my current case, this solution can't function, for example : 1989-01-01 and 1989-12-31.
This two dates start and finish the last day of week and belong to the 52nd week.
Have you an idea ?
Thanks you :)
CodePudding user response:
Solution :
''' <summary>
''' Convert the <see cref="DateTime"/> object passed as a parameter to the <see cref="DateWeek"/> object (according to ISO 8601)
''' </summary>
''' <param name="value"></param>
''' <returns></returns>
''' <remarks>https://stackoverflow.com/a/1497606/15423682</remarks>
Public Shared Function FromDateTime(value As DateTime) As DateWeek
' https://github.com/dotnet/runtime/blob/b41f1c5f2fde25d752d857a54c3af24145060cdd/src/libraries/System.Private.CoreLib/src/System/Globalization/ISOWeek.cs
' in current country (FR), first day of week is Monday
Dim _dayOfWeek As Integer = GetWeekday(value.DayOfWeek)
If (_dayOfWeek = 0) Then
_dayOfWeek = 7 ' in .Net, Sunday is 0
End If
' Get the week number for the current value
Dim week As Integer = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
value, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday
)
Dim year As Integer = value.Year
' if the current value is during week 52 and only for first month
If (week >= 52) Then
' In ISO 8601, the first Thurday is in first week.
' If the current value is before Thurday, is in previous week
' The last week of the year (52 or 53) is the one containing the last Thursday of the year.
' It is the last week to have the majority of its days (at least 4) in the year and systematically contains
' 28 December. It is also the one whose Sunday is closest to 31 December.
' It ends no earlier than 28 December or no later than 3 January (so the 4th day belongs to the first week)
' https://fr.wikipedia.org/wiki/ISO_8601#Système_de_numérotation
If (value.Month = 1 And value.Day < 4) Then
year -= 1
End If
End If
Return New DateWeek(_dayOfWeek, week, year)
End Function