Use new Date/Time/DateTime methods for extracting parts

Properties
LC0083 Info Design Code Fix Ignore Obsolete

When extracting a component from a date or time value, the traditional AL approach uses numeric-argument functions — Date2DMY(MyDate, 2) for the month, or the Format/Evaluate round-trip for time parts. The argument 2 carries no meaning at the call site; a reader must recall that 1 is day, 2 is month, 3 is year. Extracting time components is worse: it converts through a text representation with a format string like '<HOURS24>'.

Since runtime version 14.0, the Date, Time, and DateTime types have instance methods for direct component access. MyDate.Month() is self-documenting and avoids the intermediate text conversion.

Examples

TypeOld patternNew methodReturns
DateDate2DMY(MyDate, 1)MyDate.Day()Day of month
DateDate2DMY(MyDate, 2)MyDate.Month()Month
DateDate2DMY(MyDate, 3)MyDate.Year()Year
DateDate2DWY(MyDate, 1)MyDate.DayOfWeek()Day of week (1–7, Monday = 1)
DateDate2DWY(MyDate, 2)MyDate.WeekNo()Week number (1–53)
DateDate2DWY(MyDate, 3)MyDate.Year()Gets the year
TimeEvaluate(i, Format(MyTime, 2, '<HOURS24>'))MyTime.Hour()Hours (0–23)
TimeEvaluate(i, Format(MyTime, 2, '<MINUTES>'))MyTime.Minute()Minutes (0–59)
TimeEvaluate(i, Format(MyTime, 2, '<SECONDS>'))MyTime.Second()Seconds (0–59)
TimeEvaluate(i, Format(MyTime, 3, '<THOUSANDS>'))MyTime.Millisecond()Milliseconds (0–999)
DateTimeDT2Date(MyDateTime)MyDateTime.Date()Date part
DateTimeDT2Time(MyDateTime)MyDateTime.Time()Time part
procedure GetMonthOfPosting(SalesHeader: Record "Sales Header"): Integer
begin
    exit(Date2DMY(SalesHeader."Posting Date", 2)); // Use new Date/Time/DateTime methods for extracting parts [LC0083]
end;

Use the instance method on the date value directly:

procedure GetMonthOfPosting(SalesHeader: Record "Sales Header"): Integer
begin
    exit(SalesHeader."Posting Date".Month());
end;

Date2DWY(MyDate, 3) vs MyDate.Year()

Date2DWY(MyDate, 3) and MyDate.Year() are not interchangeable. Date2DWY returns the ISO week-numbering year , which can differ from the calendar year for dates in weeks that span two years:

When the input date to the Date2DWY method is in a week that spans two years, the Date2DWY method computes the output year as the year that has the most days.

System.Date2DWY(Date, Integer) Method on Microsoft Learn

December 30, 2013 falls in the week Monday December 29, 2013 through Sunday January 4, 2014 — three days in 2013, four in 2014. Date2DWY(20131230D, 3) returns 2014, while 20131230D.Year() returns 2013.

See also