将TDateTime转换为另一个时区,无论本地时区如何

Dav*_*ave 4 delphi timezone

无论用户的本地时区设置为什么,使用Delphi 2007,我都需要确定东部时区的时间(TDateTime).

我怎样才能做到这一点?当然,需要节省时间的夏令时.

Nin*_*rry 11

如果我理解正确,您希望东部时间等于当前系统时间.

为此,请使用WiNAPI功能GetSystemTime()以UTC 格式获取计算机的当前时间.UTC与时区无关,总能让您在本初子午线上获得时间.

然后,您可以使用WinAPI函数SystemTimeToTzSpecificLocalTime()从UTC时间计算任何其他给定时区的本地时间.为了SystemTimeToTzSpecificLocalTime()能够工作,您需要为其提供一个TTimeZoneInformation记录,其中填充了您要转换为的时区的正确信息.

根据2005年能源政策法案,以下样本将始终为您提供东部时间的当地时间.

function GetEasternTime: TDateTime;
var
  T: TSystemTime;
  TZ: TTimeZoneInformation;
begin
  // Get Current time in UTC
  GetSystemTime(T);

  // Setup Timezone Information for Eastern Time
  TZ.Bias:= 0;

  // DST ends at First Sunday in November at 2am
  TZ.StandardBias:= 300;
  TZ.StandardDate.wYear:= 0;
  TZ.StandardDate.wMonth:= 11; // November
  TZ.StandardDate.wDay:= 1; // First
  TZ.StandardDate.wDayOfWeek:= 0; // Sunday
  TZ.StandardDate.wHour:= 2;
  TZ.StandardDate.wMinute:= 0;
  TZ.StandardDate.wSecond:= 0;
  TZ.StandardDate.wMilliseconds:= 0;

  // DST starts at Second Sunday in March at 2am
  TZ.DaylightBias:= 240;
  TZ.DaylightDate.wYear:= 0;
  TZ.DaylightDate.wMonth:= 3; // March
  TZ.DaylightDate.wDay:= 2; // Second
  TZ.DaylightDate.wDayOfWeek:= 0; // Sunday
  TZ.DaylightDate.wHour:= 2;
  TZ.DaylightDate.wMinute:= 0;
  TZ.DaylightDate.wSecond:= 0;
  TZ.DaylightDate.wMilliseconds:= 0;

  // Convert UTC to Eastern Time
  Win32Check(SystemTimeToTzSpecificLocalTime(@TZ, T, T));

  // Convert to and return as TDateTime
  Result := EncodeDate(T.wYear, T.wMonth, T.wDay) + 
   EncodeTime(T.wHour, T.wMinute, T.wSecond, T.wMilliSeconds);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption:= 'In New York Citiy, it is now ' + DateTimeToStr(GetEasternTime);
end;
Run Code Online (Sandbox Code Playgroud)