Finding the date of monday in a week with VB.NET

前端 未结 10 1570
故里飘歌
故里飘歌 2020-12-16 12:37

I need to find a way to find the date (DD/MM/YYYY) of the Monday for any week we\'re on.

For example, for this week, monday would be 09/11/2009, and if this were nex

相关标签:
10条回答
  • 2020-12-16 13:22

    Following on from my comments to Meta-Knight's answer, here is a short function that makes the correction I mention in the comments:

    Public Function GetFirstOfLastWeek() As DateTime
    Dim today As DateTime, daysSinceMonday As Integer
        today = DateTime.Today
        daysSinceMonday = today.DayOfWeek - DayOfWeek.Monday
        If daysSinceMonday < 0 Then
            daysSinceMonday += 7
        End If
        Return today.AddDays(-daysSinceMonday)  
    End Function
    
    0 讨论(0)
  • 2020-12-16 13:26

    And if your week starts from Monday then you can use something like this:

    DateTime mondayDate = DateTime.Now.AddDays(((DateTime.Now.DayOfWeek == DayOfWeek.Sunday?7: (int)DateTime.Now.DayOfWeek) - 1)*-1);
    
    DateTime sundayDate = DateTime.Now.AddDays(7 - (DateTime.Now.DayOfWeek == DayOfWeek.Sunday?7: (int)DateTime.Now.DayOfWeek ));
    
    0 讨论(0)
  • 2020-12-16 13:31

    If Sunday is the first day of week, you can simply do this:

    Dim today As Date = Date.Today
    Dim dayDiff As Integer = today.DayOfWeek - DayOfWeek.Monday
    Dim monday As Date = today.AddDays(-dayDiff)
    

    If Monday is the first day of week:

    Dim today As Date = Date.Today
    Dim dayIndex As Integer = today.DayOfWeek
    If dayIndex < DayOfWeek.Monday Then
        dayIndex += 7 'Monday is first day of week, no day of week should have a smaller index
    End If
    Dim dayDiff As Integer = dayIndex - DayOfWeek.Monday
    Dim monday As Date = today.AddDays(-dayDiff)
    
    0 讨论(0)
  • 2020-12-16 13:32

    Another approach if Monday is the first day, is this:

     Dim today As Date = Date.Today
                    Dim dayDiff As Integer = today.DayOfWeek - DayOfWeek.Monday
                    Dim monday As Date = today.AddDays(-dayDiff)
    
                    dayDiff = DayOfWeek.Saturday - today.DayOfWeek + 1
                    Dim sunday As Date = today.AddDays(dayDiff)
    
    0 讨论(0)
提交回复
热议问题