Working with mili second DateTime with culture specific format in Delphi

738 views Asked by At

I am having below code which is working fine on my system as my date time format of the system is dd-mm-yyyy, but below code does not work where date time format of system is dd/mm/yyyy.

    try
          fmt.LongDateFormat:='dd-mm-yyyy';
          fmt.DateSeparator  :='-';
          fmt.LongTimeFormat :='hh:nn:ss.z';
          fmt.TimeSeparator  :=':'    ;

          dateTime :=42467.51801;
          strDate :=FormatDateTime('dd-mm-yyyy hh:nn:ss.z', dateTime);
          time := StrToDateTime(strDate,fmt);   

           strDate :=FormatDateTime('dd-mm-yyyy hh:nn:ss.z', time);
        ShowMessage('DateTime := ' +strDate)  ;
         except
         on e: Exception do
            ShowMessage('Exception message = '+e.Message);
end;

the same code with format dd/mm/yyyy does not work on my system. Please help me.

1

There are 1 answers

0
Remy Lebeau On

Your code is using LongDateFormat and LongTimeFormat, but StrToDateTime() does not use those values.

StrToDate() and StrToDateTime() use ShortDateFormat (and TwoDigitYearCenturyWindow, which does not apply in this case) to parse dates.

StrToTime() and StrToDateTime() use hard-coded logic to parse times. You cannot specify the order/presence of the hour/minute/second/millisecond values, you can only specify the TimeSeparator, DecimalSeparator, TimeAMString, and TimePMString values.

Try this instead:

try
  fmt.ShortDateFormat := 'dd/mm/yyyy';
  fmt.DateSeparator := '/';
  fmt.TimeSeparator := ':';
  fmt.DecimalSeparator := '.';

  dateTime := 42467.51801;
  strDate := FormatDateTime('dd/mm/yyyy hh:nn:ss.z', dateTime, fmt);
  time := StrToDateTime(strDate, fmt);

  strDate := FormatDateTime('dd/mm/yyyy hh:nn:ss.z', time, fmt);
  ShowMessage('DateTime := ' + strDate);
except
  on e: Exception do
    ShowMessage('Exception message = '+e.Message);
end;