Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

First day date in week based on particular date

4.00/5 (1 vote)
29 Nov 2010CPOL 21.7K  
Find first day of week containing given date
This function identifies the first day of week based on a particular date.

Example:
Sending 01.01.2010 will return 28.12.2009.

M | T | W | T | F | S | S
28  29  30  31   1    2    3

First date in same week as 01.01.2010 date, is 28.12.2009.

VB
''' <summary>Returns first day date in week based on specified date.</summary>
Private Function FirstDateOfWeek(ByVal dayInWeek As Date) As Date
<br />
    ' Calculate difference between specified date days of week and first day of week
    Dim Days As Integer = dayInWeek.DayOfWeek - CurrentCulture.DateTimeFormat.FirstDayOfWeek
<br />
    ' Add day difference to number of days in week then devide sum with days in week, reminder is number of days we need to substract
    Days = (7 + Days) Mod 7
<br />
    ' Substract difference of days from specified date
    Return dayInWeek.AddDays(-Days)
End Function

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)