In Delphi, date functions are available in the SysUtils and DateUtils units.
These functions help with date and time manipulation. Here are some commonly used
date functions:
1. Getting the Current Date and Time
• Date: Returns the current system date.
• Time: Returns the current system time.
• Now: Returns the current date and time.
var
CurrentDate, CurrentTime, CurrentDateTime: TDateTime;
begin
CurrentDate := Date; // e.g., 2025-03-13
CurrentTime := Time; // e.g., 14:30:45
CurrentDateTime := Now; // e.g., 2025-03-13 14:30:45
end;
2. Formatting Dates
• FormatDateTime: Formats a TDateTime value into a string.
var
FormattedDate: string;
begin
FormattedDate := FormatDateTime('yyyy-mm-dd', Now); // Example: "2025-03-
13"
end;
Basic Format Specifiers
Specifier Meaning Example Output (Now = 2025-03-13)
yyyy Full year 2025
yy Last two digits of year 25
mmmm Full month name March
mmm Short month name Mar
mm Month (2 digits) 03
m Month (1 or 2 digits) 3
dddd Full day name Thursday
ddd Short day name Thu
dd Day (2 digits) 13
d Day (1 or 2 digits) 13
3. Extracting Date Components
• DayOf(Date): Extracts the day from a date.
• MonthOf(Date): Extracts the month from a date.
• YearOf(Date): Extracts the year from a date.
uses DateUtils;
var
Year, Month, Day: Word;
begin
DecodeDate(Now, Year, Month, Day);
// Example: Year = 2025, Month = 3, Day = 13
end;
4. Adding or Subtracting Days, Months, and Years
• IncDay(Date, N): Adds N days to a date.
• IncMonth(Date, N): Adds N months to a date.
• IncYear(Date, N): Adds N years to a date.
uses DateUtils;
var
FutureDate: TDateTime;
begin
FutureDate := IncDay(Now, 10); // Adds 10 days to the current date.
end;
5. Calculating Date Differences
• DaysBetween(Date1, Date2): Returns the number of days between two dates.
• MonthsBetween(Date1, Date2): Returns the number of months between two
dates.
• YearsBetween(Date1, Date2): Returns the number of years between two dates.
uses DateUtils;
var
DiffDays: Integer;
begin
DiffDays := DaysBetween(EncodeDate(2025, 3, 13), EncodeDate(2025, 4, 13));
// Output: 31
end;
6. Checking if a Year is a Leap Year
• IsLeapYear(Year): Returns True if the year is a leap year.
var
LeapCheck: Boolean;
begin
LeapCheck := IsLeapYear(2024); // True
end;