2010-07-25 25 views
14

在我的代碼中,我遇到了一個問題。示例代碼:'23/02/2011 12:34:56'無效日期和時間

var 
    d1: tdatetime 
begin 
    d1 := strtodatetime('23/02/2011 12:34:56'); 
end; 

,但它給了錯誤:

'23/02/2011 12:34:56' is not valid date and time

出了什麼問題我在做什麼?

+2

看起來像一個語言環境的問題:這是一個有效的英國日期但不是美國的日期,例如。 – 2010-07-25 19:29:19

+5

我會在「StrToDate [Time]」函數[s]上發出警告:*「警告,這個函數取決於語言環境,可能會在其他計算機上失敗,這就是爲什麼您不應該使用字符串輸入,編輯或存儲日期,永遠不會!「*。 – 2010-07-26 06:02:11

回答

31

StrToDateTime函數使用ShortDateFormatDateSeparator的日期部分和LongTimeFormatTimeSeparator的時間部分轉換。所以你的字符串必須與這些變量匹配才能將字符串轉換爲TDateTime。相反,您可以使用StrToDateTime和TFormatSettings參數來解析字符串。

function StrToDateTime(const S: string; const FormatSettings: TFormatSettings): TDateTime; 

檢查該樣本

Var 
StrDate : string; 
Fmt  : TFormatSettings; 
dt  : TDateTime; 
begin 
fmt.ShortDateFormat:='dd/mm/yyyy'; 
fmt.DateSeparator :='/'; 
fmt.LongTimeFormat :='hh:nn:ss'; 
fmt.TimeSeparator :=':'; 
StrDate:='23/02/2011 12:34:56'; 
dt:=StrToDateTime(StrDate,Fmt); 
+0

爲什麼在'LongTimeFormat'中使用'nn'而不是'mm'需要幾分鐘? – CinCout 2016-04-12 05:26:30

+1

因爲_nn_表示分鐘,_mm_表示月份。 – RRUZ 2016-04-12 05:48:00

+0

感謝您的澄清:)沒有注意到含糊不清。 – CinCout 2016-04-12 06:27:14

2

這是由於代碼中的日期/時間格式與您的區域設置的日期/時間格式不匹配所致。

從文檔(D2009):

The S parameter must use the current locale's date/time format. In the US, this is commonly MM/DD/YY HH:MM:SS format. Specifying AM or PM as part of the time is optional, as are the seconds. Use 24-hour time (7:45 PM is entered as 19:45, for example) if AM or PM is not specified.

如果您使用的是老德爾福,StrToDateTime可能要求特定的格式。從文檔(在這種情況下D5):

The S parameter must be in the MM/DD/YY HH:MM:SS format. Specifying AM or PM as part of the time is optional, as are the seconds. Use 24-hour time (7:45 PM is entered as 19:45, for example) if AM or PM is not specified.

4

使用VarToDateTime可能是簡單了很多,它只是工作開箱:

uses Variants; 

newDateTime := VarToDateTime('23/02/2011 12:34:56'); 
+0

如果日期時間格式類似於「06. okt。2015」,則甚至StrToDateTime(DateTimeToStr(Now))失敗。但VarToDateTime(而不是StrToDateTime)工作正常。這似乎是最好的選擇。 – 2015-10-06 12:35:01