The function WORK_WEEK calculates the week from the date of input IDATE.
The week starts with 1 for the first week of the year. The first Thursday
of the year is always in the first week. If a year starts with a Thursday or
end on a Thursday this year has 53 calendar weeks. If the first day of the
year a Tuesday, Wednesday or Thursday so the week begins one early as
December of last year. If the first day of the year is Friday, Saturday or
Sunday, the last week of the year extends into January. The calculation is
done in accordance with ISO8601.
As the work week (Work Week ) International is not always used consistent,
before the application of the function is to clarify, whether the work
week according to ISO8601 is desired in the desired application function.
SCL Language Codes:
Kod:
FUNCTION WORK_WEEK : INT
VAR_INPUT
idate : DATE; (*Exmple: 31.12.2007*)
END_VAR
VAR
d1 : DATE;
w1 : INT;
ds: DWORD;
yr: INT;
w31: INT;
w01: INT;
wm: INT;
END_VAR
(* berechne den 1.1 des jahres von idate. *)
yr := YEAR_OF_DATE(idate);
d1 := YEAR_BEGIN(yr);
(* wochentag von d1 *)
w1 := DAY_OF_WEEK(d1);
(* offset des montags der eletzten KW des vorjahres *)
(* wenn der erste tag des jahres größer als donnerstag ist dann beginnt die letzte kw am montag davor *)
(* wenn der erste tag des jahres ein donnerstag oder kleiner ist beginnt die erste kw 2 montage davor *)
IF w1 < 5 THEN
ds := DATE_TO_DWORD(d1) - INT_TO_DWORD(w1+6) * 86400;
ELSE
ds := DATE_TO_DWORD(d1) - INT_TO_DWORD(w1-1) * 86400;
END_IF;
(* kalenderwoche des eingangsdatums *)
WORK_WEEK := DWORD_TO_INT((DATE_TO_DWORD(idate) - ds) / 604800);
(* korrektur wenn work_week = 0 *)
IF work_week = 0 THEN
(* work_week needs to be 53 when 1.jan of the year before is thursday or dec 31. is thursday. *)
(* first and last weekday of a year is equal and one more day for a leap_year. *)
IF w1 > 1 THEN w31 := w1 - 1; ELSE W31 := 7; END_IF;
IF LEAP_YEAR(yr - 1) AND w31 > 1 THEN w01 := W31 - 1; ELSE w1 := 7; END_IF;
(* if first or last day of a year is a thursday, the year has 53 weeks *)
WORK_WEEK := 52 + BOOL_TO_INT(w31 = 4 OR w01 = 4);
ELSE
(* end of year calculation *)
(* calculated the first and last weekday *)
IF leap_year(yr) THEN
IF w1 < 7 THEN w31 := w1 + 1; ELSE w31 := 1; END_IF;
ELSE
w31 := w1;
END_IF;
(* if first or last day is thursday then the year has 53 weeks otherwise only 52 *)
wm := 52 + BOOL_TO_INT(w31 = 4 OR w1 = 4);
IF WORK_WEEK > wm THEN WORK_WEEK := 1; END_IF;
END_IF;