TrySystemTimeToDateTime (C++)

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

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  TDateTime newLDateTime, LDateTime;
  TSystemTime LSystemTime;
  Word LHour, LMin, LSec, LMSec;
  Word LYear, LMonth, LDay, LDOW;
  String msgstr;

  // 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);

  if (TrySystemTimeToDateTime(LSystemTime, LDateTime))
  {
	DecodeDateFully(LDateTime, LYear, LMonth, LDay, LDOW);
    DecodeTime(LDateTime, LHour, LMin, LSec, LMSec);

	if ((LSystemTime.wYear == LYear) && (LSystemTime.wMonth == LMonth) &&
	   // Delphi's DayOfWeek is 1 more than Windows, must substract 1 from LDOW
	   (LSystemTime.wDay == LDay) && (LSystemTime.wDayOfWeek == LDOW - 1) &&
	   (LSystemTime.wHour == LHour) && (LSystemTime.wMinute == LMin) &&
	   (LSystemTime.wSecond == LSec) && (LSystemTime.wMilliseconds == LMSec))
	  msgstr = "This time encoded and decoded correctly through TrySystemTimeToDateTime.";
	else
	  msgstr = "This time encode and decode disagree through TrySystemTimeToDateTime.";
  }
  else
	msgstr = "This time did not encode correctly through TrySystemTimeToDateTime.";
  try
  {
	newLDateTime = SystemTimeToDateTime(LSystemTime);
  }
  catch (Exception &exception)
  {
	MessageDlg(msgstr+sLineBreak+exception.ToString()+" for SystemTimeToDateTime.", mtError, TMsgDlgButtons() << mbOK, 0);
  }
  if (1)
	{
	  msgstr = msgstr+sLineBreak+"No exception for SystemTimeToDateTime";
	  if (LDateTime == newLDateTime)
		msgstr = msgstr+sLineBreak+"TrySystemTimeToDateTime and SystemTimeToDateTime agree.";
	  else
		msgstr = msgstr+sLineBreak+"TrySystemTimeToDateTime and SystemTimeToDateTime disagree.";
	  MessageDlg(msgstr, mtError, TMsgDlgButtons() << mbOK, 0);
	}
}

Uses