Tech Tip: Calculating the first and last day of a Week from a Date
PRODUCT: 4D | VERSION: 11.4 | PLATFORM: Mac & Win
Published On: September 10, 2009
Sometimes you need to find information about a week and you only have a date within the week, for example, the current date. The following routine allows you to find the first and last day of the week given a date. The following code assumes that the week begins with Sunday and ends with Saturday.
`................................................................... ` Project Method: Util_Calculate_Week ` Description: return first and last day of week based on a date ` Parameters: $1 - Date - date to calculate week start and end for ` Returns: $2 - Pointer to Date - First Day of the Week ` $3 - Pointer to Date - Last Day of the Week ` Util_Calculate_Week(current date;->$thisweekstart;->$thisweekend) `................................................................... C_DATE($Date_d;$Date1_d;$Date2_d) C_INTEGER($DayNumber_l) C_DATE($1) C_POINTER($2;$3) $Date_d:=$1 $DayNumber_l:=Day number($1) Case of : ($DayNumber_l=1) $Date1_d:=$Date_d $Date2_d:=$Date_d+6 : ($DayNumber_l=2) $Date1_d:=$Date_d-1 $Date2_d:=$Date_d+5 : ($DayNumber_l=3) $Date1_d:=$Date_d-2 $Date2_d:=$Date_d+4 : ($DayNumber_l=4) $Date1_d:=$Date_d-3 $Date2_d:=$Date_d+3 : ($DayNumber_l=5) $Date1_d:=$Date_d-4 $Date2_d:=$Date_d+2 : ($DayNumber_l=6) $Date1_d:=$Date_d-5 $Date2_d:=$Date_d+1 : ($DayNumber_l=7) $Date1_d:=$Date_d-6 $Date2_d:=$Date_d End case $2->:=$Date1_d $3->:=$Date2_d |
Many thanks for the optimized routine as well.
C_POINTER(vThisWeek1_d;vThisWeek2_d)
As the idea of the code is to return the two dates, I guess best is to change the two last lines to:
$2->:=$Date1_d
$3->:=$Date2_d
And call the method such as:
Util_Calculate_Week(current date;->$thisweekfirstday;->$thisweeklastday)
But the code is too complex, it could be drastically reduced with a simple calculation:
C_DATE($1;vThisWeek1_d)
C_POINTER($2;$3)
vThisWeek1_d:=$1-(Day number($1))+1
$2->:=vThisWeek1_d
$3->:=vThisWeek1_d+6
The whole code can be reduced to 5 lines...
Thanks to J. Buchwitz, Germany, for reporting this.