DelphiBasics
StrToDate
Function
Converts a date string into a TDateTime value SysUtils unit
1  function StrToDate ( const Date : string ) : TDateTime;
2  function StrToDate ( const Date : string; const FormatSettings : TFormatSettings ) : TDateTime;
Description
The StrToDate function attempts to convert a date as a string Date into a TDateTime value.
 
The date string must adhere to the format of the ShortDateFormat value, and use the DateSeparator character to separate the day, month and year values.
 
The default format in the UK is day/month/year, where :
 
The day  must be 1..31 (depending on month/year)
The month  must be 1..12
The year  must be 0..9999 (optional)

 
Omitting the year results in the use of the current year.
 
Note that year 0015, for example, must be given with the century digits; 15 on its own would be seen as a recent year.
 
If the year is 2 digits, the century is determined by the TwoDigitYearCenturyWindow value.
 
The time is set to 0 - the start of the specified day.
 
Any errors in the date string will yield EConvertError.
 
Version 2 of this function is for use within threads. You furnish the FormatSettings record before invoking the call. It takes a local copy of global formatting variables that make the routine thread safe.
Related commands
DateSeparator The character used to separate display date fields
DateToStr Converts a TDateTime date value to a string
ShortDateFormat Compact version of the date to string format
StrToDateTime Converts a date+time string into a TDateTime value
StrToTime Converts a time string into a TDateTime value
TwoDigitYearCenturyWindow Sets the century threshold for 2 digit year string conversions
 Download this web site as a Windows program.


 
Example code : Showing 2 and 4 digit year date string conversions
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
 
unit Unit1;
 
interface
 
uses
  SysUtils,   // Unit containing the StrToDate command
  Forms, Dialogs;
 
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;
 
var
  
Form1: TForm1;
 
implementation
{$R *.dfm} // Include form definitions
 
procedure TForm1.FormCreate(Sender: TObject);

var
  myDate : TDateTime;

begin
  myDate := StrToDate('15/03/75');
  ShowMessage('15/03/75   = '+DateTimeToStr(myDate));
  myDate := StrToDate('01/01/2075');
  ShowMessage('01/01/2075 = '+DateTimeToStr(myDate));
end;
 
end.
Hide full unit code
   15/03/75   = 15/03/1975
   01/01/2075 = 01/01/2075
 
 
Delphi Programming Neil Moffatt 2002 - 2014. All rights reserved.  |  Contact the author  |  Home Page