我正在使用Delphi7.
我将日期格式设置为yyyymmdd(可以采用任何日期格式而不使用分隔符).当我尝试StrToDate('20170901')它时,它会抛出错误.
我想支持所有有效的日期格式(可以由不同区域中的不同客户端使用.)
我试过VarToDateTime但它也没用.
如果DateToStr()也存在同样的问题,请引导我完成.
您收到错误,因为您的输入字符串与您的机器的日期/时间字符串的区域设置不匹配.
通常情况下,我建议使用StrToDate()功能的SysUtils单位,设置其全球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;
Run Code Online (Sandbox Code Playgroud)
不幸的是,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;
Run Code Online (Sandbox Code Playgroud)
该DateToStr()功能也受区域设置的限制.但是,它确实允许DateSeparator在输出中省略.所以,您可以:
使用DateToStr(),将全局ShortDateFormat变量设置为所需的格式:
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;
Run Code Online (Sandbox Code Playgroud)从TDateTime使用单元中的DecodeDate()函数中提取单个日期组件SysUtils,然后根据需要使用年/月/日值格式化您自己的字符串:
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;
Run Code Online (Sandbox Code Playgroud)要将字符串转换为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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2453 次 |
| 最近记录: |