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

前端 未结 10 1569
故里飘歌
故里飘歌 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:10

    I just did this in a project I'm working on --I promise, it's correct. This is a method that returns the nth monday after the given date. If the given date is a monday, it returns the next monday.

    Public Function GetSubsequentMonday(ByVal startDate As DateTime, ByVal subsequentWeeks As Integer) As DateTime
        Dim dayOfWeek As Integer = CInt(startDate.DayOfWeek)
        Dim daysUntilMonday As Integer = (Math.Sign(dayOfWeek) * (7 - dayOfWeek)) + 1
        'number of days until the next Monday
        Return startDate.AddDays(CDbl((daysUntilMonday + (7 * (subsequentWeeks - 1)))))
    End Function
    
    0 讨论(0)
  • 2020-12-16 13:11

    There is a day of week method that you can use

    Dim instance As DateTime
    Dim value As DayOfWeek
    
    value = instance.DayOfWeek
    

    see: http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx

    0 讨论(0)
  • 2020-12-16 13:13
    =Format(DateAdd("d", (-1 * WeekDay(Date.Today()) + 2), Date.Today()), "dd/MM/yyyy")
    
    0 讨论(0)
  • 2020-12-16 13:14

    A simple method should get you what you want:

        private static DateTime GetMondayForWeek(DateTime inputDate)
        {
            int daysFromMonday = inputDate.DayOfWeek - DayOfWeek.Monday;
            return inputDate.AddDays(-daysFromMonday);
        }
    

    You could also extend it for any day that you want as well:

        private static DateTime GetDayForWeek(DateTime inputDate, DayOfWeek inputDay)
        {
            int daysAway = inputDate.DayOfWeek - inputDay;
            return inputDate.AddDays(-daysAway);
        }
    

    To call the first example just use something like:

    DateTime mondayDate = GetMondayForWeek(new DateTime(2009, 11, 15));
    Console.WriteLine(mondayDate);
    
    0 讨论(0)
  • 2020-12-16 13:15

    DateTime.DayOfWeek is an enum that indicates what day a given date is. As Monday is 1, you can find the Monday of the current week using the following code:

    Dim monday As DateTime = Today.AddDays((Today.DayOfWeek - DayOfWeek.Monday) * -1)
    
    0 讨论(0)
  • 2020-12-16 13:21
    Dim dayOfWeek = CInt(DateTime.Today.DayOfWeek)
    Dim startOfWeek = DateTime.Today.AddDays(+1 * dayOfWeek).ToShortDateString
    Dim endOfWeek = DateTime.Today.AddDays(6 + dayOfWeek).AddSeconds(+1).ToShortDateString
    MessageBox.Show(startOfWeek)
    MessageBox.Show(endOfWeek)
    

    Example: If today is 03/09/2020,
    startOfWeek will be 07/09/2020 and
    endOfWeek will be 13/09/2020.

    0 讨论(0)
提交回复
热议问题