Search code examples
datetimedelphidelphi-xeweek-number

Retrieve Year from week number


Using Embarcadero Delphi, I need to populate a table with week number and the week year. The problem is at the end of December and starting January.

First case: Date "29/12/2024": is in the year 2024 and is referred to the 52° week of 2024. So I'll insert a record like: WEEK NUMBER = 52 WEEK YEAR = 2024

Second case: Date "30/12/2024": is in the year 2024 but is referred to the 1° week of 2025. So I need to insert a record like: WEEK NUMBER = 1 WEEK YEAR = 2025

How can I calculate this dynamically? Monday is the first date of the week


Solution

  • You can use this procedure:

    USES System.DateUtils;
    
    PROCEDURE GetWeek(D : TDate ; OUT Week,Year : Cardinal);
      BEGIN
        Week:=WeekOf(D); Year:=YearOf(D);
        CASE MonthOf(D) OF
           1 : IF Week>50 THEN DEC(Year);
          12 : IF Week<50 THEN INC(Year)
        END
      END;
    

    It will return the Week and the corresponding Year for any given date in the Julian Calendar.