TrySystemTimeToDateTime (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example uses the SysUtils function TrySystemTimeToDateTime and compares the output and behavior with the old SysUtils function SystemTimeToDateTime.

Code

procedure TForm1.Button1Click(Sender: TObject);

var
   newLDateTime, LDateTime: TDateTime;
  LSystemTime: TSystemTime;
  LHour, LMin, LSec, LMSec: Word;
  LYear, LMonth, LDay, LDOW: Word;
  msgstr: String;
   ExceptionObj : TObject;



begin
   // Construct valid date/time
  LSystemTime.wYear := StrToInt(Edit1.Text);
   LSystemTime.wMonth := StrToInt(Edit2.Text);
   LSystemTime.wDayOfWeek := StrToInt(Edit3.Text);
   LSystemTime.wDay := StrToInt(Edit4.Text);
   LSystemTime.wHour := StrToInt(Edit5.Text);
  LSystemTime.wMinute := StrToInt(Edit6.Text);
  LSystemTime.wSecond := StrToInt(Edit7.Text);
  LSystemTime.wMilliseconds := StrToInt(Edit8.Text);

   ExceptionObj := nil;
   if TrySystemTimeToDateTime(LSystemTime, LDateTime) then
  begin
    DecodeDateFully(LDateTime, LYear, LMonth, LDay, LDOW);
    DecodeTime(LDateTime, LHour, LMin, LSec, LMSec);

    if (LSystemTime.wYear = LYear) and (LSystemTime.wMonth = LMonth) and
      // Delphi's DayOfWeek is 1 more than Windows, must substract 1 from LDOW
      (LSystemTime.wDay = LDay) and (LSystemTime.wDayOfWeek = LDOW - 1) and
      (LSystemTime.wHour = LHour) and (LSystemTime.wMinute = LMin) and
      (LSystemTime.wSecond = LSec) and (LSystemTime.wMilliseconds = LMSec) then
      msgstr := 'This time encoded and decoded correctly through TrySystemTimeToDateTime.'
    else
      msgstr := 'This time encode and decode disagree through TrySystemTimeToDateTime.';
  end
   else
    msgstr := 'This time did not encode correctly through TrySystemTimeToDateTime.';
  try
    newLDateTime:= SystemTimeToDateTime(LSystemTime);
   except
    begin
    ExceptionObj := ExceptObject;
    MessageDlg(msgstr+sLineBreak+ExceptionObj.ToString+' for SystemTimeToDateTime.', mtError, [mbOK], 0);
    end;
  end;
  if ExceptionObj = nil then
    begin
      msgstr := msgstr+sLineBreak+'No exception for SystemTimeToDateTime';
      if LDateTime = newLDateTime then
        msgstr := msgstr+sLineBreak+'TrySystemTimeToDateTime and SystemTimeToDateTime agree.'
      else
        msgstr := msgstr+sLineBreak+'TrySystemTimeToDateTime and SystemTimeToDateTime disagree.';
      MessageDlg(msgstr, mtError, [mbOK], 0);
    end
end;

Uses