Use new Date/Time/DateTime methods for extracting parts
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
| Type | Old pattern | New method | Returns |
|---|---|---|---|
| Date | Date2DMY(MyDate, 1) | MyDate.Day() | Day of month |
| Date | Date2DMY(MyDate, 2) | MyDate.Month() | Month |
| Date | Date2DMY(MyDate, 3) | MyDate.Year() | Year |
| Date | Date2DWY(MyDate, 1) | MyDate.DayOfWeek() | Day of week (1–7, Monday = 1) |
| Date | Date2DWY(MyDate, 2) | MyDate.WeekNo() | Week number (1–53) |
Date2DWY(MyDate, 3) | MyDate.Year() | ||
| Time | Evaluate(i, Format(MyTime, 2, '<HOURS24>')) | MyTime.Hour() | Hours (0–23) |
| Time | Evaluate(i, Format(MyTime, 2, '<MINUTES>')) | MyTime.Minute() | Minutes (0–59) |
| Time | Evaluate(i, Format(MyTime, 2, '<SECONDS>')) | MyTime.Second() | Seconds (0–59) |
| Time | Evaluate(i, Format(MyTime, 3, '<THOUSANDS>')) | MyTime.Millisecond() | Milliseconds (0–999) |
| DateTime | DT2Date(MyDateTime) | MyDateTime.Date() | Date part |
| DateTime | DT2Time(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
- Date Data Type on Microsoft Learn
- Time Data Type on Microsoft Learn
- DateTime Data Type on Microsoft Learn
- Business Central 2024 wave 2 (BC25): New Date/Time/DateTime methods by Yun Zhu
- Exploring New Date/Time/DateTime Methods in Business Central on YouTube