Link to home
Start Free TrialLog in
Avatar of surfbored
surfboredFlag for United States of America

asked on

Safely Enter Date String into TDateTimePicker

I want to convert a string that looks like this "2009-12-31" into a TDate, SAFELY.

I'm worried that my TDateTimePicker will not load the date correctly on machines with different regional settings (possibly confusing the day and the month).

Can anyone with experience offer advice/code?

Thanks.
Avatar of Geert G
Geert G
Flag of Belgium image

in your program you can set the regional settings for your program

at startup you can set any of the global delphi variables

Application.UpdateFormatSettings := False;
will make sure they stay like that when somebody changes windows regional settings while your program is running
procedure TMainForm.FormCreate(Sender: TObject);
begin
  DecimalSeparator := '.';
  ShortDateFormat := 'YYYY-MM-DD';
  Application.UpdateFormatSettings := False;
end;

Open in new window

Avatar of surfbored

ASKER

Geert:

Thanks for your suggestion, but I would still like the user to see the date in the format they expect to see it, otherwise they're likely to enter the wrong value.

I know I can convert the date properly from the DateTimePicker (in fact I do that already), I just don't know how to put it back into the DateTimePicker correctly. Any other suggestions?

 
function YourStrToDate(aString: string): TDateTime;
var sdf: string;
begin
  sdf := ShortDateFormat;
  try
    ShortDateFormat := 'YYYY-MM-DD';
    Result := StrToDate(aString);
  finally
    ShortDateFormat := sdf;
  end;
end;
the use that result to set the Data in the DateTimePicker

dtp.Date := YourStrToDate('2009-12-31');
Geert:

This is almost exactly the code I tried myself, but both yours and mine return the same exception:

EConvertError ... ''2008-12-31' is not a valid date'.

:(
Avatar of gtrifidis
gtrifidis

Well you could you use
TryStrToDate or TryStrToDateTime

From Delphi Help File
Call TryStrToDateTime to parse a string that specifies a date and time value. If S does not contain a valid date, TryStrToDateTime returns false.

The above applies to TryStrToDate
function TryStrToDateTime(const S: string; out Value: TDateTime): Boolean; overload;
function TryStrToDate(const S: string; out Value: TDateTime): Boolean; overload;

Open in new window

gtrifidis:

Thanks for the heads up on the functions, they should prove useful, but I'm not sure how they solves the current problem. If you have a clever use for these, I'm all ears! :)


ASKER CERTIFIED SOLUTION
Avatar of Geert G
Geert G
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for hanging in there. This answer was a great help!