Search code examples
delphipascal

Delphi Convert TArray<Strings> to DateTime


I want to convert all the values contained in a TArray to TDateTime type. ConvertDS and ConvertDE are TDateTime variable and StoringData is the TArray

StoringData : TArray<String>;
SetLength(StoringData,2);
  for x := 0 to High(StoringData) do
    for c := 0 to  High(StoringData[x]) do
      begin
         StoringData[x]   :=  TotTime;
         StoringData[c]   :=  DataCovertedS;
      end;


ConvertDS := (StrToDateTime(StoringData[c]));
ConvertDE := (StrToDateTime(StoringData[c+1]));

Data is splitted like this

        Year  := Copy(aData,0,4);
        Month := Copy(aData,5,2);
        Day   := Copy(aData,7,2);
        DataCovertedS := Concat(Year+'-'+Month+'-'+Day);

When i try to execute it the StrToDateTime doesn't work.


Solution

  • It turns out that the actual question is "How to obtain a TDateTime value from a string in the format 'YYYY-MM-DD'?".

    Fortunately, this is not hard. Every time you use a new function in an API, you read its documentation. In this case, the StrToDate documentation says the following:

    S must consist of two or three numbers, separated by the character defined by the DateSeparator global variable or its TFormatSettings equivalent. The order for month, day, and year is determined by the ShortDateFormat global variable or its TFormatSettings equivalent--possible combinations are m/d/y, d/m/y, and y/m/d.

    So, we can do it like this:

    // Define the date format:
    var FS := TFormatSettings.Invariant;
    FS.DateSeparator := '-';
    FS.ShortDateFormat := 'y/m/d';
    
    // Just an example of a string in this format:
    const S = '2021-05-31';
    
    // StrToDate will parse this using FS:
    var D := StrToDate(S, FS);
    
    // Test:
    ShowMessage(DateToStr(D));