Jump to content
Oscar Hernández

FormatDateTime in Delphi 12

Recommended Posts

Hello everyone,

I am working with Delphi 12 and using some functions to convert TDateTime to String and vice versa. However, while testing the FormatDateTime function, I noticed an issue. When I use the format dd/mm/yyyy, specifying the slash (/) as the date separator, but my system's short date format is set to aaaa-MM-dd (using a hyphen as the separator), the output is in dd-mm-yyyy format instead of the expected dd/mm/yyyy.

Is this a bug, or is there a specific reason for this behavior?

Here is a snapshot of my short date format and the result of the example above.

 

image.thumb.png.f9827e5e4a2a0f09da638d44b22201bc.png

image.png

Edited by Oscar Hernández
I have updated the image to use the TDateTime variable.

Share this post


Link to post

You are using the version of FormatDateTime() that relies on global variables initialized with your PC's locale settings. For instance, the '/' specifier is not a literal slash character, it is a placeholder that uses the global DateSeparator variable in the SysUtils unit. This is documented behavior.
 

You can update those globals to customize things like the date/time separators, but this affects the whole app, and is not thread-safe. When you need custom formatting that is locale-agnostic, you should use the version of FormatDateTime() that takes a TFormatSettings parameter, eg:

procedure TForm1.Button1Click(Sender: TObject);
var
  lDate: TDateTime;
  lFmt: TFormatSettings;
begin
  lFmt := TFormatSettings.Create;
  lFmt.DateSeparator := '/';
  lDate := EncodeDate(2025, 3, 26);
  Edit1.Text := FormatDateTime('dd/mm/yyyy', lDate, lFmt);
end;

The alternative is to wrap desired literal text with quotes in your format string, eg:

procedure TForm1.Button1Click(Sender: TObject);
var
  lDate: TDateTime;
begin
  lDate := EncodeDate(2025, 3, 26);
  Edit1.Text := FormatDateTime('dd"/"mm"/"yyyy', lDate);
end;
Edited by Remy Lebeau
  • Like 4
  • Thanks 2

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×