Mirror

A Better TDateTimePicker (Views: 710)


Problem/Question/Abstract:

A Better TDateTimePicker

Answer:

Although the TDateTimePicker component is quite useful sometimes (I still prefer my own date-picking components), it lacks an important feature: the ability to set your own date/time format, or even a mix of both. It's restricted to the two Windows date/time format: the short and the long format. With that on my mind, I wrote a TDateTimePicker descendant, TASDateTimePickerEx that will allow you to change the format of the component to whatever you want. Without further delay, here's the code for the new component:

unit ASDTPickEx;

interface

uses
  Windows, Classes, ComCtrls;

type
  TASDateTimePickerEx = class(TDateTimePicker)
  private
    FFormatStr: string;
    procedure SetFormatStr(AValue: string);
    { Private declarations }
  protected
    { Protected declarations }
  public
    constructor Create(AOwner: TComponent); override;
    { Public declarations }
  published
    property FormatString: string read FFormatStr
      write SetFormatStr;
    { Published declarations }
  end;

procedure Register;

implementation

uses CommCtrl;

procedure Register;
begin
  RegisterComponents('New', [TASDateTimePickerEx]);
end;

constructor TASDateTimePickerEx.Create(AOwner: TComponent);
begin
  inherited;
  FFormatStr := 'MM/dd/YYYY';
end;

procedure TASDateTimePickerEx.SetFormatStr(AValue: string);
begin
  try
    Perform(DTM_SETFORMAT, 0, longint(pchar(AValue)));
    FFormatStr := AValue;
  except
    Perform(DTM_SETFORMAT, 0, longint(pchar(FFormatStr)));
  end;
end;

end.
  
After installing the component (it has been tested on both Delphi 3 and 4), you can play with the FormatString property, by assigning it values like 'ddd, MMMM/dd/yyyy', or whatever you want. I mean, you can create whatever format you want for either the date or the time.

Download source code

<< Back to main page