我正在使用Delphi7。
我的日期格式设置为yyyymmdd(可以不带分隔符使用任何日期格式)。当我尝试使用StrToDate('20170901')
时,它会抛出错误。
我想支持所有有效的日期格式(不同客户端在不同区域可能使用不同格式)。
我已经尝试过VarToDateTime
,但也无法正常工作。
如果对于DateToStr()也有相同的问题,请也指导一下我。
您之所以出现错误,是因为您的输入字符串与您机器的日期/时间格式设置不匹配。
通常情况下,我建议您使用SysUtils
单元中的StrToDate()
函数,在此之前设置其全局变量ShortDateFormat
和DateSeparator
,然后在恢复它们(Delphi 7之前没有引入TFormatSettings
记录),例如:
uses
..., SysUtils;
var
OldShortDateFormat: string;
OldDateSeparator: Char;
input: string;
dt: TDateTime;
begin
input := ...;
OldShortDateFormat := ShortDateFormat;
OldDateSeparator := DateSeparator;
ShortDateFormat := 'yyyymmdd'; // or whatever format you need...
DateSeparator := '/'; // or whatever you need
try
dt := StrToDate(input);
finally
ShortDateFormat := OldShortDateFormat;
DateSeparator := OldDateSeparator;
end;
// use dt as needed...
end;
很遗憾,StrToDate()
函数要求输入字符串在日期元素之间有分隔符(如2017/09/01
),但您的输入字符串没有分隔符(20170901
)。即使ShortDateFormat
格式中未指定分隔符,StrToDate()
也不允许将 DateSeparator
设置为#0
。
因此只有一种选择-手动解析字符串以提取各个组件,然后使用SysUtils
单元中的EncodeDate()
函数进行编码,例如:
uses
..., SysUtils;
var
wYear, wMonth, wDay: Word;
input: string;
dt: TDateTime;
begin
input := ...;
wYear := StrToInt(Copy(input, 1, 4));
wMonth := StrToInt(Copy(input, 5, 2));
wDay := StrToInt(Copy(input, 7, 2));
// or in whatever order you need...
dt := EncodeDate(wYear, wMonth, wDay);
// use dt as needed...
end;
DateToStr()
函数同样受到区域设置的影响。然而,它允许在输出中省略 DateSeparator
。因此,您可以选择:
use DateToStr()
, setting the global ShortDateFormat
variable to the desired format:
uses
..., SysUtils;
var
OldShortDateFormat: string;
dt: TDateTime;
output: string;
begin
dt := ...;
OldShortDateFormat := ShortDateFormat;
ShortDateFormat := 'yyyymmdd'; // or whatever format you need...
try
output := DateToStr(dt);
finally
ShortDateFormat := OldShortDateFormat;
end;
// use output as needed...
end;
extract the individual date components from the TDateTime
using the DecodeDate()
function in the SysUtils
unit, and then format your own string with the year/month/day values however you want:
uses
..., SysUtils;
var
wYear, wMonth, wDay: Word;
dt: TDateTime;
output: string;
begin
dt := ...;
DecodeDate(dt, wYear, wMonth, wDay);
output := Format('%.4d%.2d%.2d', [wYear, wMonth, wDay]);
// use output as needed...
end;
要将该字符串转换为 TDateTime
,请将字符串拆分为年、月和日组件,并将它们传递给 EncodeDate()
函数。
var
myStr: string;
myDate: TDate;
begin
myStr := '20170901';
myDate := EncodeDate(
StrToInt(Copy(MyStr, 1, 4)),
StrToInt(Copy(MyStr, 5, 2)),
StrToInt(Copy(MyStr, 7, 2))
);
...
end;
02/04/2017
是什么意思?是2月4日还是4月2日?那么20112004
又是什么意思?是2011年4月20日还是2004年11月20日呢?你不可能处理所有的日期格式。你可以处理已知的格式,也可以根据用户环境和本地化来处理格式,但是不可能处理所有可能的格式 - 总会有多个可用的解释。 - J...