How to convert a historical timestamp to a differe

2019-02-23 02:05发布

I need to convert a historical timestamp from GMT to BST in Delphi (Win32). I can't use the current regional settings in the OS to do the conversion because it won't have the correct daylight saving (DST) offset for the historical time.

Is there a VCL API or Win32 API I can use?

1条回答
放荡不羁爱自由
2楼-- · 2019-02-23 02:18

Delphi TZDB may be of use. It's main feature is that has a class that handles times using the tz database, which, if it contains "historical enough" data, would let you use UTC as an intermediary. The tz database aims to have rules for all the time zones throughout the world and the various time shifts for things like leap years, daylight savings time, calendar changes, etc. as they relate to UTC since the Unix epoch (Midnight, Jan 1, 1970).

Once you have the package installed, usage would be along the lines of the following:

function ConvertFromGMTToBST(const AGMTTime: TDateTime): TDateTime;
var
   tzGMT, tzBST: TTimeZone;
   UTCTime: TDateTime;
begin
    tzGMT := TBundledTimeZone.GetTimeZone('GMT');
    tzBST := TBundledTimeZone.GetTimeZone('BST');
    UTCTime := tzGMT.ToUniversalTime(AGMTTime);
    Result := tzBST.ToLocalTime(UTCTime);
end;

The above relies on a few assumptions. First of all, that GMT and BST are valid aliases in the tz database. If not, then you'll need to find the closest cities. (e.g. America/New_York). The second one is that I'm pretty sure my code is Delphi XE+ specific. TZDB claims to work on Delphi 6 and newer (and FreePascal) though, so the adjustments to work should be minor.

Unfortunately regional dates and times are very complex, especially if you stretch back much before the 20th century.

查看更多
登录 后发表回答