我用的是Delphi7。
我将日期格式设置为yyyymmdd (可以采用任何没有分隔符的日期格式)。当我尝试StrToDate('20170901')
时,它是抛出错误。
我希望支持所有有效的日期格式(可供不同区域的不同客户端使用)。
我尝试过使用VarToDateTime
,但它也不起作用。
如果DateToStr()也有同样的问题,也请指导我。
发布于 2017-09-01 18:26:57
因为输入字符串与机器的日期/时间字符串的区域设置不匹配,所以会出现错误。
通常,我建议在StrToDate()
单元中使用SysUtils
函数,预先设置其全局ShortDateFormat
和DateSeparator
变量,然后恢复它们(Delphi7在引入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
)。StrToDate()
不允许在解析字符串时将DateSeparator
设置为#0
,即使ShortDateFormat
没有指定格式中的任何分隔符。
因此,这只剩下一个选项--手动解析字符串以提取各个组件,然后在EncodeDate()
单元中使用SysUtils
函数,例如:
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
。所以,你可以:
DateToStr()
,将全局ShortDateFormat
变量设置为所需的格式:
使用.,SysUtils;var OldShortDateFormat: string;dt: TDateTime;output: string;begin dt := .;OldShortDateFormat := ShortDateFormat;ShortDateFormat := 'yyyymmdd';//或任何您需要的格式.尝试输出:= DateToStr(dt);最终ShortDateFormat := OldShortDateFormat;end;//根据需要使用输出.结束;TDateTime
单元中的DecodeDate()
函数从SysUtils
中提取各个日期组件,然后用您想要的年份/月/日值格式化您自己的字符串:
使用.,SysUtils;var wYear,wMonth,wDay: Word;dt: TDateTime;output: string;begin dt := .;DecodeDate(dt,wYear,wMonth,wDay);输出:=格式(‘%.4d%.2d%.2d’,wYear,wMonth,wDay);//根据需要使用输出.结束;发布于 2017-09-01 16:41:24
若要将该字符串转换为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;
https://stackoverflow.com/questions/46000313
复制相似问题