2017-09-24 270 views
-1

使用Delphi XE6。我需要能夠將UTC日期和時間轉換爲任何美國時區。 現在,我在我的數據庫中使用UTC的所有日期時間加上每個時區用戶的數字。像EST一樣5。UTC日期和時間任何時區德爾福

我有這個,但它總是讓我回到同一時間,無論夏令時。

function SendRouteOnCallNotify.GetMyLocalTime(UTCDate,UTCTime: TDateTime; HoursToAdd: Integer): TDateTime; 
var 
    T: TSystemTime; 
    TZ: TTimeZoneInformation; 
    DT: TDateTime; 
begin 
    // Get Current time in UTC 
    //GetSystemTime(T); 
    ReplaceTime(UTCDate,UTCTime); 
    DateTimeToSystemTime(UTCDate,T); 
    // Setup Timezone Information for Eastern Time 
    TZ.Bias:= 0; 

    // DST ends at First Sunday in November at 2am 
    TZ.StandardBias:= (HoursToAdd * 60); 
    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:= (HoursToAdd * 60); 
    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; 

感謝您的任何幫助。

+1

當您調試時,它在哪一行偏離您的期望?如何? –

回答

2

MSDN Documentation解釋TIME_ZONE_INFORMATION結構(略)的有趣的領域:

TTimeZoneInformation記錄有3場調整相關標準時間和夏令時(DST),以UTC:BiasStandardBiasDaylightBias。這些的正常用法是:

  • Bias保持UTC和本地(標準)時間之間的分鐘差異。
  • StandardBias在標準時間內保持分鐘數來調整偏差。這通常是零。
  • DaylightBias保存分鐘數並將其添加到Bias字段以形成DST期間使用的總偏差。通常這是-60。

在你的情況,當你有Bias字段設置爲0,並用小時數(從DB)調整StandardBiasDaylightBias領域仍然需要調整DaylightBias的額外60分鐘,F。恩。

TZ.StandardBias:= (HoursToAdd * 60); 

TZ.DaylightBias:= ((HoursToAdd-1) * 60); // note the -1 hour 
相關問題