Welcome

首页 / 软件开发 / Delphi / Delphi获取格林威治时间并转换到北京时间

Delphi获取格林威治时间并转换到北京时间2013-12-12 cnblogs 万一
uses Winapi.msxml, System.DateUtils; //实时获取网络时间的函数, 得到的是格林威治时间; 默认从 sohu 服务器获取, 因为它最快, 平均只需 15 毫秒function GetNetTime(aUrl: WideString = "http://www.sohu.com"): string;beginwith CoXMLHTTP.Create dobeginopen("Post", aUrl, False, EmptyParam, EmptyParam);send(EmptyParam);Result := getResponseHeader("Date");end;end; //格林威治时间(字符串)转换到北京时间function GMT2BjDateTime(const GMT: string): TDateTime;varA: TArray<string>;beginA := GMT.Split([",", " "], ExcludeEmpty); //XE4 支持 with TStringList.Create dobeginCommaText := "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);varstrGMT: string;bjDateTime: TDateTime;beginstrGMT := GetNetTime();bjDateTime := GMT2BjDateTime(strGMT); ShowMessageFmt("%s"#13#10"%s", [strGMT, DateTimeToStr(bjDateTime)]);end;
在真正实用中, 我把 GMT2BjDateTime 函数换成了:

function GMT2BjDateTime(const GMT: string): TDateTime;varA: TArray<string>;Y,M,D,H,N,S: Word;beginA := GMT.Split([",", " ", ":"], ExcludeEmpty); with TStringList.Create dobeginCommaText := "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;