Week number input returns crazy full week output

2019-09-11 00:53发布

问题:

I would like some feedback on what's wrong with these codes. I'm trying to output a full week based on a week number. For instance if I input "2014/45" I would like to output all dates spanning from November 2nd to November 8th. Now I need to figure out the first date in that week (hence November 2nd) before grabbing the rest of the days and this is where everything gets messed up for me. This is what I've come up with:

' getyear = 2014, getweek = 45
Dim DateOfFirstWeekDay As DateTime = GetDateOfFirstDayOfWeek(getyear, getweek)    
Dim FirstDateInSequence As DateTime = CDate(DateAdd("d", _
                        CInt(Abs(Integer.Parse(Weekday(DateOfFirstWeekDay, WeekStartsWith))) * -1) + 1, _
                        DateOfFirstWeekDay)).ToShortDateString()

Protected Friend Shared Function GetDateOfFirstDayOfWeek(ByVal getyear As Nullable(Of Integer), _
                                                 ByVal getweek As Nullable(Of Integer)) As DateTime
    Dim firstWeekDay As DateTime = GetFirstDayOfWeek(newYearDay)

    If getweek = 1 Then
        getweek -= 1
    End If

    Return DateAdd(DateInterval.WeekOfYear, CInt(getweek), firstWeekDay)
End Function

Protected Friend Shared Function GetFirstDayOfWeek(ByVal dt As DateTime) As DateTime
    If dt.DayOfWeek = DayOfWeek.Sunday Then
        Return dt.AddDays(-6)
    Else
        Return dt.AddDays(1 - CInt(dt.DayOfWeek))
    End If
End Function

As my question implies November 2nd is not the result I get. Instead FirstDateInSequence returns December 22, 2013 when I input 2014/45. It's pretty safe to assume something fails me here. I just can't get my head around it. I'd like your point of view to this. Where should I focus my attention in the code above?

回答1:

I'm having a hard time quickly following your code logic. So here's mine.

You could start by finding the first day of the first week of that year

    Dim d As New DateTime(year, 1, 1)

    d = d.AddDays(-d.DayOfWeek)

And then add the number of days (week_number -1) * 7

    d = d.AddDays((week_number - 1) * 7)

I do a -1 since I assume that week_number will be equal to 1 to get the first week. Since d is already equal to the first week, we start counting at 0.

To get the last day, just add 6 (or 7) days to the result