22

Delphi 5で、使用する実際の形式を指定できるTDateTimeに文字列を変換する方法はありますか?

私は、さまざまなワークステーションからタスクを受け入れるジョブプロセッサに取り組んでいます。タスクにはさまざまなパラメーターがあり、そのうちのいくつかは日付ですが、(残念ながら、私の制御ではありませんが)文字列として渡されます。ジョブは異なるワークステーションから取得できるため、文字列として日付をフォーマットするために使用される実際の日時フォーマットは異なる場合があります(もちろん、実際には異なります)

グーグルで調べてみると、私が見つけた唯一の簡単な解決策は、変数をこっそり変更し、ShortDateFormat後で元の値に戻すことでした。ShortDateFormatはグローバル変数であり、スレッド環境で作業しているため、これが機能する唯一の方法は、アクセスをすべて同期することです。これは完全に受け入れられません(元に戻せません)。

ライブラリコードをSysUtilsユニットから独自のメソッドにコピーし、グローバル変数の代わりに指定された形式で動作するように調整することもできますが、見逃したより適切なものがあるかどうか疑問に思っています。

アップデート

もっと簡潔に言えば:

文字列をTDateTimeに変換するために使用する正確な形式を指定するオプションが追加された、StrToDate(または)のようなものが必要です。StrToDateTime

4

8 に答える 8

32

代わりにVarToDateTimeを使用してください。文字列でさらに多くの日付形式をサポートし、それらを自動的に変換します。

var
  DateVal: TDateTime;
begin
  DateVal := VarToDateTime('23 Sep 2010');
  ShowMessage(DateToStr(DateVal));
end;

Delphi 5を使用しているようです。Delphiの一部のバージョンでは、uses句にバリアントを追加する必要があります。それ以降のほとんどのバージョンでは、それが追加されています。Delphi5がどのカテゴリに分類されたかは覚えていません。

于 2010-09-24T17:45:04.377 に答える
8

FreePascalのdateutilsユニット用にこのようなルーチンを作成しました。移植が必要な場合は、簡単に移植できるはずです。

コード:

http://svn.freepascal.org/cgi-bin/viewvc.cgi/trunk/packages/rtl-objpas/src/inc/dateutil.inc?revision=30628&view=co

(コードはファイルの最後にある最後の(巨大な)プロシージャです)

ドキュメンテーション:

http://www.freepascal.org/docs-html/rtl/dateutils/scandatetime.html

formatdatetimeの完全な逆ではなく、いくつかの拡張機能があることに注意してください。

  • FormatDateTimeの逆数は、100%逆数ではありません。これは、たとえばタイムトークンをフォーマット文字列に2回入れることができ、scandatetimeがどちらの時間を選択するかわからないためです。

  • hnのような文字列は安全に元に戻すことはできません。たとえば、1:2(1の2分後)は12を配信し、12:00として解析され、「n」部分の文字が欠落します。

    • 末尾の文字は無視されます。
    • 東アジアのフォーマット文字はウィンドウのみであるため、サポートされていません。
    • MBCSはサポートされていません。
  • 拡張機能

    • #9は空白を食べます。
    • パターンの最後の空白はオプションです。
    • ?任意の文字に一致します。
    • 上記の文字を引用して、実際に文字と一致させます。

(これらのコメントは、アジアのサポートが後で追加されたという意味で少し時代遅れだと思いますが、よくわかりません)

于 2010-09-24T12:52:24.980 に答える
7

それ以降のバージョンのDelphiは、文字列変換関数に追加のTFormatSettings引数をとることができます。TFormatSettingsは、さまざまな形式のグローバル変数(ShortDateFormat、LongDateFormatなど)を含む構造体です。したがって、スレッドセーフな方法で、さらには1回の呼び出しでも、これらの値をオーバーライドできます。

これがどのバージョンのDelphiで導入されたかは覚えていませんが、Delphi5以降であったことは間違いありません。

そうですね、私が知る限り、ShortDateFormatへのすべてのアクセスを同期するか、別の関数を使用する必要があります。

于 2010-09-24T12:27:03.920 に答える
7

これが関数、その2つのヘルパー、およびすべてのコードです。正確な日時形式を使用して文字列を解析するために作成しました。

class function TDateTimeUtils.TryStrToDateExact(const S, DateFormat: string; PivotYear: Integer;
        out Value: TDateTime): Boolean;
var
    Month, Day, Year: Integer;
    Tokens: TStringDynArray;
    CurrentToken: string;
    i, n: Integer;
    Partial: string;
    MaxValue: Integer;
    nCurrentYear: Integer;

    function GetCurrentYear: Word;
    var
        y, m, d: Word;
    begin
        DecodeDate(Now, y, m, d);
        Result := y;
    end;
begin
    Result := False;
{
    M/dd/yy

    Valid pictures codes are

        d       Day of the month as digits without leading zeros for single-digit days.
        dd      Day of the month as digits with leading zeros for single-digit days.
        ddd Abbreviated day of the week as specified by a LOCALE_SABBREVDAYNAME* value, for example, "Mon" in English (United States).
                Windows Vista and later: If a short version of the day of the week is required, your application should use the LOCALE_SSHORTESTDAYNAME* constants.
        dddd    Day of the week as specified by a LOCALE_SDAYNAME* value.

        M       Month as digits without leading zeros for single-digit months.
        MM      Month as digits with leading zeros for single-digit months.
        MMM Abbreviated month as specified by a LOCALE_SABBREVMONTHNAME* value, for example, "Nov" in English (United States).
        MMMM    Month as specified by a LOCALE_SMONTHNAME* value, for example, "November" for English (United States), and "Noviembre" for Spanish (Spain).

        y       Year represented only by the last digit.
        yy      Year represented only by the last two digits. A leading zero is added for single-digit years.
        yyyy    Year represented by a full four or five digits, depending on the calendar used. Thai Buddhist and Korean calendars have five-digit years. The "yyyy" pattern shows five digits for these two calendars, and four digits for all other supported calendars. Calendars that have single-digit or two-digit years, such as for the Japanese Emperor era, are represented differently. A single-digit year is represented with a leading zero, for example, "03". A two-digit year is represented with two digits, for example, "13". No additional leading zeros are displayed.
        yyyyy   Behaves identically to "yyyy".

        g, gg   Period/era string formatted as specified by the CAL_SERASTRING value.
                The "g" and "gg" format pictures in a date string are ignored if there is no associated era or period string.


        PivotYear
                The maximum year that a 1 or 2 digit year is assumed to be.
                The Microsoft de-factor standard for y2k is 2029. Any value greater
                than 29 is assumed to be 1930 or higher.

                e.g. 2029:
                    1930, ..., 2000, 2001,..., 2029

                If the PivotYear is between 0 and 99, then PivotYear is assumed to be
                a date range in the future. e.g. (assuming this is currently 2010):

                    Pivot   Range
                    0       1911..2010  (no future years)
                    1       1912..2011
                    ...
                    98      2009..2108
                    99      2010..2099  (no past years)

                0 ==> no years in the future
                99 ==> no years in the past
}
    if Length(S) = 0 then
        Exit;
    if Length(DateFormat) = 0 then
        Exit;

    Month := -1;
    Day := -1;
    Year := -1;

    Tokens := TDateTimeUtils.TokenizeFormat(DateFormat);
    n := 1; //input string index
    for i := Low(Tokens) to High(Tokens) do
    begin
        CurrentToken := Tokens[i];
        if CurrentToken = 'MMMM' then
        begin
            //Long month names, we don't support yet (you're free to write it)
            Exit;
        end
        else if CurrentToken = 'MMM' then
        begin
            //Short month names, we don't support yet (you're free to write it)
            Exit;
        end
        else if CurrentToken = 'MM' then
        begin
            //Month, with leading zero if needed
            if not ReadDigitString(S, n, 2{MinDigits}, 2{MaxDigits}, 1{MinValue}, 12{MaxValue}, {var}Month) then Exit;
        end
        else if CurrentToken = 'M' then
        begin
            //months
            if not ReadDigitString(S, n, 1{MinDigits}, 2{MaxDigits}, 1{MinValue}, 12{MaxValue}, {var}Month) then Exit;
        end
        else if CurrentToken = 'dddd' then
        begin
            Exit; //Long day names, we don't support yet (you're free to write it)
        end
        else if CurrentToken = 'ddd' then
        begin
            Exit; //Short day names, we don't support yet (you're free to write it);
        end
        else if CurrentToken = 'dd' then
        begin
            //If we know what month it is, and even better if we know what year it is, limit the number of valid days to that
            if (Month >= 1) and (Month <= 12) then
            begin
                if Year > 0 then
                    MaxValue := MonthDays[IsLeapYear(Year), Month]
                else
                    MaxValue := MonthDays[True, Month]; //we don't know the year, assume it's a leap year to be more generous
            end
            else
                MaxValue := 31; //we don't know the month, so assume it's the largest

            if not ReadDigitString(S, n, 2{MinDigits}, 2{MaxDigits}, 1{MinValue}, MaxValue{MaxValue}, {var}Day) then Exit;
        end
        else if CurrentToken = 'd' then
        begin
            //days
            //If we know what month it is, and even better if we know what year it is, limit the number of valid days to that
            if (Month >= 1) and (Month <= 12) then
            begin
                if Year > 0 then
                    MaxValue := MonthDays[IsLeapYear(Year), Month]
                else
                    MaxValue := MonthDays[True, Month]; //we don't know the year, assume it's a leap year to be more generous
            end
            else
                MaxValue := 31; //we don't know the month, so assume it's the largest

            if not ReadDigitString(S, n, 1{MinDigits}, 2{MaxDigits}, 1{MinValue}, MaxValue{MaxValue}, {var}Day) then Exit;
        end
        else if (CurrentToken = 'yyyy') or (CurrentToken = 'yyyyy') then
        begin
            //Year represented by a full four or five digits, depending on the calendar used.
            {
                Thai Buddhist and Korean calendars have five-digit years.
                The "yyyy" pattern shows five digits for these two calendars,
                    and four digits for all other supported calendars.
                Calendars that have single-digit or two-digit years, such as for
                    the Japanese Emperor era, are represented differently.
                    A single-digit year is represented with a leading zero, for
                    example, "03". A two-digit year is represented with two digits,
                    for example, "13". No additional leading zeros are displayed.
            }
            if not ReadDigitString(S, n, 4{MinDigits}, 4{MaxDigits}, 0{MinValue}, 9999{MaxValue}, {var}Year) then Exit;
        end
        else if CurrentToken = 'yyy' then
        begin
            //i'm not sure what this would look like, so i'll ignore it
            Exit;
        end
        else if CurrentToken = 'yy' then
        begin
            //Year represented only by the last two digits. A leading zero is added for single-digit years.
            if not ReadDigitString(S, n, 2{MinDigits}, 2{MaxDigits}, 0{MinValue}, 99{MaxValue}, {var}Year) then Exit;

            nCurrentYear := GetCurrentYear;
            Year := (nCurrentYear div 100 * 100)+Year;

            if (PivotYear < 100) and (PivotYear >= 0) then
            begin
                //assume pivotyear is a delta from this year, not an absolute value
                PivotYear := nCurrentYear+PivotYear;
            end;

            //Check the pivot year value
            if Year > PivotYear then
                Year := Year - 100;
        end
        else if CurrentToken = 'y' then
        begin
            //Year represented only by the last digit.
            if not ReadDigitString(S, n, 1{MinDigits}, 1{MaxDigits}, 0{MinValue}, 9{MaxValue}, {var}Year) then Exit;

            nCurrentYear := GetCurrentYear;
            Year := (nCurrentYear div 10 * 10)+Year;

            if (PivotYear < 100) and (PivotYear >= 0) then
            begin
                //assume pivotyear is a delta from this year, not an absolute value
                PivotYear := nCurrentYear+PivotYear;
            end;

            //Check the pivot year value
            if Year > PivotYear then
                Year := Year - 100;
        end
        else
        begin
            //The input string should contains CurrentToken starting at n
            Partial := Copy(S, n, Length(CurrentToken));
            Inc(n, Length(CurrentToken));
            if Partial <> CurrentToken then
                Exit;
        end;
    end;

    //If there's still stuff left over in the string, then it's not valid
    if n <> Length(s)+1 then
    begin
        Result := False;
        Exit;
    end;

    if Day > MonthDays[IsLeapYear(Year), Month] then
    begin
        Result := False;
        Exit;
    end;

    try
        Value := EncodeDate(Year, Month, Day);
    except
        Result := False;
        Exit;
    end;
    Result := True;
end;


class function TDateTimeUtils.TokenizeFormat(fmt: string): TStringDynArray;
var
    i: Integer;
    partial: string;

    function IsDateFormatPicture(ch: AnsiChar): Boolean;
    begin
        case ch of
        'M','d','y': Result := True;
        else Result := False;
        end;
    end;
begin
    SetLength(Result, 0);

    if Length(fmt) = 0 then
        Exit;

    //format is only one character long? If so then that's the tokenized entry
    if Length(fmt)=1 then
    begin
        SetLength(Result, 1);
        Result[0] := fmt;
    end;

    partial := fmt[1];
    i := 2;
    while i <= Length(fmt) do
    begin
        //If the characters in partial are a format picture, and the character in fmt is not the same picture code then write partial to result, and reset partial
        if IsDateFormatPicture(partial[1]) then
        begin
            //if the current fmt character is different than the running partial picture
            if (partial[1] <> fmt[i]) then
            begin
                //Move the current partial to the output
                //and start a new partial
                SetLength(Result, Length(Result)+1);
                Result[High(Result)] := partial;
                Partial := fmt[i];
            end
            else
            begin
                //the current fmt character is more of the same format picture in partial
                //Add it to the partial
                Partial := Partial + fmt[i];
            end;
        end
        else
        begin
            //The running partial is not a format picture.
            //If the current fmt character is a picture code, then write out the partial and start a new partial
            if IsDateFormatPicture(fmt[i]) then
            begin
                //Move the current partial to the output
                //and start a new partial
                SetLength(Result, Length(Result)+1);
                Result[High(Result)] := partial;
                Partial := fmt[i];
            end
            else
            begin
                //The current fmt character is another non-picture code. Add it to the running partial
                Partial := Partial + fmt[i];
            end;
        end;

        Inc(i);
        Continue;
    end;

    //If we have a running partial, then add it to the output
    if partial <> '' then
    begin
        SetLength(Result, Length(Result)+1);
        Result[High(Result)] := partial;
    end;
end;

class function TDateTimeUtils.ReadDigitString(const S: string; var Pos: Integer;
            MinDigits, MaxDigits: Integer; MinValue, MaxValue: Integer;
            var Number: Integer): Boolean;
var
    Digits: Integer;
    Value: Integer;
    Partial: string;
    CandidateNumber: Integer;
    CandidateDigits: Integer;
begin
    Result := False;
    CandidateNumber := -1;
    CandidateDigits := 0;

    Digits := MinDigits;
    while Digits <= MaxDigits do
    begin
        Partial := Copy(S, Pos, Digits);
        if Length(Partial) < Digits then
        begin
            //we couldn't get all we wanted. We're done; use whatever we've gotten already
            Break;
        end;

        //Check that it's still a number
        if not TryStrToInt(Partial, Value) then
            Break;

        //Check that it's not too big - meaning that getting anymore wouldn't work
        if (Value > MaxValue) then
            Break;

        if (Value >= MinValue) then
        begin
            //Hmm, looks good. Keep it as our best possibility
            CandidateNumber := Value;
            CandidateDigits := Digits;
        end;

        Inc(Digits); //try to be greedy, grabbing even *MORE* digits
    end;

    if (CandidateNumber >= 0) or (CandidateDigits > 0) then
    begin
        Inc(Pos, CandidateDigits);
        Number := CandidateNumber;
        Result := True;
    end;
end;
于 2010-09-29T15:39:13.640 に答える
4

これが後のDelphiでどのように解決されたかを知りたい場合は、ここでもう少し最新の(Delphi 6のように見える)sysutils.pasのソースを確認できます。

http://anygen.googlecome.com/.../SysUtils.pas

StrToDateTimeパラメータを取るオーバーロードされたバージョンを確認してTFormatSettingsください。

function StrToDateTime(const S: string;
  const FormatSettings: TFormatSettings): TDateTime; overload;
于 2010-09-25T05:58:52.083 に答える
1

RegExprライブラリを使用します(https://github.com/masterandrey/TRegExpr

var
    RE: TRegExpr;

begin
    RE := TRegExpr.Create;
    try
        RE.Expression := '^(\d\d\d\d)/(\d\d)/(\d\d)T(\d\d):(\d\d):(\d\d)$';
        if RE.Exec( Value ) then
        begin
            try
                Result := EncodeDate( StrToInt( RE.Match[1] ),
                                      StrToInt( RE.Match[2] ),
                                      StrToInt( RE.Match[3] ) ) +
                          EncodeTime( StrToInt( RE.Match[4] ),
                                      StrToInt( RE.Match[5] ),
                                      StrToInt( RE.Match[6] ),
                                      0 )
            except
                raise EConvertError.Create( 'Invalid date-time: ' + Value )
            end
        end
        else
            raise EConvertError.Create( 'Bad format: ' + Value )
    finally
        RE.Free
    end
end;
于 2017-05-18T15:21:15.550 に答える
0

私はそれを逆に行きます。私が見ているように、あなたはあなたが自分で言及したものの約2つのオプションがあります

  • ShortDateFormatを調整し、それにアクセスするすべての同期を維持します。
  • 受信している文字列の形式がわかっている場合(どういうわけか、そうする必要があります)、文字列をジャグリングして、最初に現在のshortdateformatで文字列を取得します。その後、(ジャグリングされた)文字列をに変換しTDateTimeます。

たとえば2010年4月5日のフォーマットをどのように決定するのだろうか。

program DateTimeConvert;
{$APPTYPE CONSOLE}
uses
  SysUtils;


function GetPart(const part, input, format: string): string;
var
  I: Integer;
begin
  for I := 1 to Length(format) do
    if Uppercase(format[I]) = Uppercase(part) then
      Result := Result + input[I];
end;

function GetDay(const input, format: string): string;
begin
  Result := GetPart('d', input, format);
  if Length(Result) = 1 then Result := SysUtils.Format('0%0:s', [Result]);
end;

function GetMonth(const input, format: string): string;
begin
  Result := GetPart('m', input, format);
  if Length(Result) = 1 then Result := SysUtils.Format('0%0:s', [Result]);
end;

function GetYear(const input, format: string): string;
begin
  Result := GetPart('y', input, format);
end;

function ConvertToMyLocalSettings(const input, format: string): string;
begin
  Result := SysUtils.Format('%0:s/%1:s/%2:s', [GetDay(input, format), GetMonth(input, format), GetYear(input, format)]);
end;

begin
  Writeln(ConvertToMyLocalSettings('05/04/2010', 'dd/mm/yyyy'));
  Writeln(ConvertToMyLocalSettings('05-04-2010', 'dd-mm-yyyy'));
  Writeln(ConvertToMyLocalSettings('5-4-2010', 'd-m-yyyy'));
  Writeln(ConvertToMyLocalSettings('4-5-2010', 'm-d-yyyy'));
  Writeln(ConvertToMyLocalSettings('4-05-2010', 'M-dd-yyyy'));
  Writeln(ConvertToMyLocalSettings('05/04/2010', 'dd/MM/yyyy'));
  Readln;
end.
于 2010-09-24T12:25:19.210 に答える
0

何が欲しいのかわかりません。Delphi 5はもう使用していませんが、関数StrToDateTimeが含まれていると確信しています。これを使用すると、フォーマット設定を使用して文字列をTDateTimeに変換できます。次に、FormatDateTimeを使用して、このようなTDateTimeを任意の形式に変換できます。これにより、任意の日付形式を使用できます。

于 2010-09-24T12:15:10.517 に答える