按年和月获取周数

时间:2018-02-21 13:41:15

标签: vb.net

如何根据给定的年,月和周数(当月的周数)获得Firstdayofweek和Lastdayofweek?

我能够获得FirstdayofWeek,但是当我在第2周尝试2月(2018年,2月1日)时,输出日期不正确。

Dim firstDayOfWeek As date
firstDayOfWeek = DateSerial(2018, 2, 1) 'february 2018
firstDayOfWeek = DateAdd("ww", 1, firstDayOfWeek)  'week 2

输出:

  

2/8/2018 12:00:00 AM

预期产出:

  

firstdayofweek:2/5/2018
  lastdayofweek:2/9/2018

1 个答案:

答案 0 :(得分:0)

根据您已有的信息创建自己的功能:

Public Function FirstDateOfWeekByMonth(ByVal year As Integer, ByVal month as Integer, ByVal weekOfYear As Integer) As DateTime
    Dim jan1 As DateTime = New DateTime(year, month, 1)
    Dim daysOffset As Integer = DayOfWeek.Thursday - jan1.DayOfWeek
    Dim firstThursday As DateTime = jan1.AddDays(daysOffset)
    Dim cal = CultureInfo.CurrentCulture.Calendar
    Dim firstWeek As Integer = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)
    Dim weekNum = weekOfYear
    If firstWeek <= 1 Then
        weekNum -= 1
    End If

    Dim result = firstThursday.AddDays(weekNum * 7)
    Return result.AddDays(-3)
End Function 

和用法:

Dim FirstDay as DateTime = FirstDateOfWeekByMonth(2018, 2 , 1) 'First Week of 2018 Feb
Dim LastDay as DateTime = FirstDay.AddDays(4) 'Add 4 days to get Friday

Console.WriteLine("firstdayofweek: " + FirstDay)
Console.WriteLine("lastdayofweek: " + LastDay)

得到你:

firstdayofweek: 2/5/2018 
lastdayofweek: 2/9/2018