程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> 隨便找個網站獲取格林威治時間, 並轉換到北京時間

隨便找個網站獲取格林威治時間, 並轉換到北京時間

編輯:Delphi


uses Winapi.msxml, System.DateUtils;

//實時獲取網絡時間的函數, 得到的是格林威治時間; 默認從 sohu 服務器獲取, 因為它最快, 平均只需 15 毫秒
function GetNetTime(aUrl: WideString = 'http://www.sohu.com'): string;
begin
  with CoXMLHTTP.Create do
  begin
    open('Post', aUrl, False, EmptyParam, EmptyParam);
    send(EmptyParam);
    Result := getResponseHeader('Date');
  end;
end;

//格林威治時間(字符串)轉換到北京時間
function GMT2BjDateTime(const GMT: string): TDateTime;
var
  A: TArray<string>;
begin
  A := GMT.Split([',', ' '], ExcludeEmpty); //XE4 支持

  with TStringList.Create do begin
    CommaText := 'Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12';
    A[2] := Values[A[2]];
    Free;
  end;

  Result := StrToDateTime(Format('%s/%s/%s %s', [A[3], A[2], A[1], A[4]]), FormatSettings.Create(2052));
  Result := Result + 8/24; //換算成北京時間
end;

//測試
procedure TForm1.Button1Click(Sender: TObject);
var
  strGMT: string;
  bjDateTime: TDateTime;
begin
  strGMT := GetNetTime();
  bjDateTime := GMT2BjDateTime(strGMT);

  ShowMessageFmt('%s'#13#10'%s', [strGMT, DateTimeToStr(bjDateTime)]);
end;


在真正實用中, 我把 GMT2BjDateTime 函數換成了:

function GMT2BjDateTime(const GMT: string): TDateTime;
var
  A: TArray<string>;
  Y,M,D,H,N,S: Word;
begin
  A := GMT.Split([',', ' ', ':'], ExcludeEmpty);

  with TStringList.Create do begin
    CommaText := 'Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12';
    A[2] := Values[A[2]];
    Free;
  end;

  Y := StrToIntDef(A[3], YearOf(Now));
  M := StrToIntDef(A[2], MonthOf(Now));
  D := StrToIntDef(A[1], DayOf(Now));
  H := StrToIntDef(A[4], HourOf(Now));
  N := StrToIntDef(A[5], MinuteOf(Now));
  S := StrToIntDef(A[6], SecondOf(Now));

  Result := EncodeDateTime(Y, M , D, H, N, S, 0);
  Result := Result + 8/24; //換算成北京時間
end;

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved