开发者

Delphi DateTimeFormat returning wrong year

I have a form that allows users to enter a date of birth:

ie: 4/16/40

Then when the user processes the form there's a function that checks it's length, adds leading zeros, parses the date and then uses FormatDateTime to just return the year of birth:

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;

using this code the strTemp is calculated as 204开发者_Go百科0 instead of 1940. Can anyone help me figure out how to make it show 1940 in strTemp? Do I have to change the form to accept a 4 digit year?

Thanks, Leslie


Your best option is to only accept 4-digit years, but the RTL does support changing the way 2-digit days are handled. The TwoDigitYearCenturyWindow global variable, or the TFormatSettings.TwoDigitYearCenturyWindow field control this. The RTL documentation says:

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

So if you're only parsing birthdays, you should be able to set TwoDigitCenturyWindow to 99 or 100 and it will always give older dates.


Yep! Ten years after the fact, we're still running into the Y2K bug. It's probably best to explicitly require a 4-digit date.

But if you don't, you need some sort of code that makes a judgment if it receives a 2-digit year. For example, if it's less than the current year (10), then it's a 2000 number, otherwise, it's a 1900 number. That makes sense for birthdates, although it will trip up if you register someone older than 100, of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜