實時獲取網絡時間 並轉換為北京時間的函數



unit
Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,Winapi.msxml, System.DateUtils, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Label1: TLabel; Label2: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} //實時獲取網絡時間的函數, 得到的是格林威治時間; 默認從 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; //格林威治時間(字符串)轉換到北京時間 1 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; //格林威治時間(字符串)轉換到北京時間 2 function GMT2BjDateTime2(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; bjDateTime2: TDateTime; begin strGMT := GetNetTime(); bjDateTime := GMT2BjDateTime(strGMT); bjDateTime2 := GMT2BjDateTime2(strGMT); Label1.Caption:=strGMT + #10 + DateTimeToStr(bjDateTime); Label2.Caption:=strGMT + #10 + DateTimeToStr(bjDateTime2); end; end.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM