Jump to content
Registration disabled at the moment Read more... ×
bravesofts

TDateTime Extension for Day Name Lookup with Offset and Locale

Recommended Posts

unit API.DateUtils;

interface

uses
  System.SysUtils,
  System.DateUtils;

type
  TDateTimeHelper = record helper for TDateTime
  // Get the future day or the past day in same-function..
    function DayOfWeek(const aDaysCount: Integer; aLocaleName: string = ''): string;

  end;

implementation

function TDateTimeHelper.DayOfWeek(const aDaysCount: Integer; aLocaleName: string): string;
//const
//  cDaysSysUtils : array[1..7] of string =(
//   'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
//    );
//  cDaysDateUtils : array[1..7] of string =(
//   'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'
//    );

var
  LDisplayFormat: TFormatSettings;
  LTargetDate: TDateTime;
begin
  if aLocaleName <> '' then
    LDisplayFormat := TFormatSettings.Create(aLocaleName)
  else
    LDisplayFormat := TFormatSettings.Create; // default OS locale

  LTargetDate := IncDay(Self, aDaysCount);

//  Result := cDaysSysUtils[System.SysUtils.DayOfWeek(LTargetDate)];

//  Result := cDaysDateUtils[System.DateUtils.DayOfTheWeek(LTargetDate)];

  Result := FormatDateTime('dddd', LTargetDate, LDisplayFormat);
end;

end.

then use it like this:


procedure TMainView.BtnTestClick(Sender: TObject);
begin
  ShowMessage('In 200 days, it will be: ' + Today.DayOfWeek(200, 'ar-DZ'));
  ShowMessage('200 days ago, it was: ' + Today.DayOfWeek(-200, 'ar-DZ'));
end;

Helper for TDateTime to get the name of the day (e.g., Monday, Tuesday) based on a given day offset.
It supports both future and past dates by adding or subtracting a number of days.

The helper function returns the localized name of the day of the week for the current date, adjusted by aDaysCount.
If aLocaleName is provided, it uses that locale; otherwise, the default operating system locale is used.

Share this post


Link to post

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now

×