Delphi DateTimeFormat 返回错误的年份

标签 delphi datetime formatting

我有一个允许用户输入出生日期的表单:

即:4/16/40

然后,当用户处理表单时,有一个函数检查其长度,添加前导零,解析日期,然后使用 FormatDateTime 返回出生年份:

strTemp := strPostedByDOB;
If Length(strTemp) = 5
  then strTemp = '0' + strTemp;
if Length(strTemp) = 6 
  then begin
    strTemp := Copy(strTemp, 1 ,2) + '/' + copy(strTemp, 3, 2) + '/' + Copy(strTemp, 5, 2);
    strTemp := FormatDateTime('YYYY', StrToDate(strTemp));
end
else strTemp := EmptyStr;

使用此代码,strTemp 计算为 2040 而不是 1940。谁能帮我弄清楚如何使其在 strTemp 中显示 1940?我是否必须更改表格才能接受 4 位数的年份?

谢谢, 莱斯利

最佳答案

您的最佳选择是仅接受 4 位数年份,但 RTL 确实支持更改 2 位数日期的处理方式。 TwoDigitYearCenturyWindow 全局变量或 TFormatSettings.TwoDigitYearCenturyWindow 字段对此进行控制。 RTL 文档说:

TwoDigitYearCenturyWindow - Determines what century is added to two digit years when converting string dates to numeric dates. This value is subtracted from the current year before extracting the century. This can be used to extend the lifetime of existing applications that are inextricably tied to 2 digit year data entry. The best solution to Year 2000 (Y2k) issues is not to accept 2 digit years at all - require 4 digit years in data entry to eliminate century ambiguities.

Examples:

Current TwoDigitCenturyWindow  Century  StrToDate() of:
Year    Value                  Pivot    '01/01/03' '01/01/68' '01/01/50'
-------------------------------------------------------------------------
1998    0                      1900     1903       1968       1950
2002    0                      2000     2003       2068       2050
1998    50 (default)           1948     2003       1968       1950
2002    50 (default)           1952     2003       1968       2050
2020    50 (default)           1970     2003       2068       2050

因此,如果您只解析生日,则应该能够将 TwoDigitCenturyWindow 设置为 99 或 100,并且它将始终给出较旧的日期。

关于Delphi DateTimeFormat 返回错误的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647772/

相关文章:

delphi - 如何避免函数结果被函数内部的Free破坏?

T 按钮上的 Delphi 2010 图像褪色/闪烁

php - 在 PHP 中添加时间

python - 在python中将字符串转换为日期时间并与当前时间进行比较

java - Java 中的 String.format() 和十六进制数字

asp.net - 如何在GridView中使用DataFormatString修改货币格式

delphi - 如何在Delphi中解析JSON字符串?

macos - Firemonkey 应用程序 - 在 OS X 下运行时启动外部应用程序

c# - 强制本地 DateTime 序列化

r - 如何使用 R 的 sprintf 创建固定宽度的字符串,并在 END 处填充空白?