Mega Code Archive

 
Categories / Delphi / System
 

Convert a UTC time to your current system time

Title: Convert a UTC time to your current system time Question: How can I get my systems localtime from an Coordinated Universal Time (UTC)? Answer: I was about to write a FTP component and found out that most FTP servers support the MDTM command (which sends back the date & time for a specific file) However, the RFC standard for the MDTM command says that the server should return the time value in UTC time. Therefore I needed a routine for converting the UTC time to my systems local time to be able to get the correct time when the file was changed/created. See code below for a description on how this is done using the Windows API GetTimeZoneInformation and SystemTimeToTzSpecificLocalTime //---------------------------------------------------------------------------- uses SysUtils, windows; function UTCToSystemTime(UTC : TDateTime) : TDateTime; var TimeZoneInf : _TIME_ZONE_INFORMATION; UTCTime,LocalTime: TSystemTime; begin if GetTimeZoneInformation(TimeZoneInf) DatetimetoSystemTime(UTC,UTCTime); if SystemTimeToTzSpecificLocalTime(@TimeZoneInf,UTCTime,LocalTime) then begin result := SystemTimeToDateTime(LocalTime); end else result := UTC; end else result := UTC; end; //---------------------------------------------------------------------------- Below is an extension to the TNMFTP component which introducies the MDTM command. const Cont_MDTM = 'MDTM '; function TNMFTP.GetFileDate(RemoteFile : string) : TDateTime; var DateStr : String; Year, Month, Day, Hour, Min, Sec, EndChar: Word; begin DoCommand(Cont_MDTM+RemoteFile); {Send get Current directory Command} DateStr := trim(NthWord(TransactionReply,' ',2)); try // Remove all aprts after . in DateStr EndChar := Pos('.',DateStr); if EndChar 0 then DateStr := Copy(DateStr,1,EndChar-1); if length(DateStr) = 8 then begin if length(DateStr) 14 then begin // Assume that the FTP server has a y2k bug and reports years after 1999 as 19100 Year := 1900 + StrToIntDef(Copy(DateStr,2,3),0); Month := StrToIntDef(Copy(DateStr,6,2),1); Day := StrToIntDef(Copy(DateStr,8,2),1); Hour := StrToIntDef(Copy(DateStr,10,2),0); Min := StrToIntDef(Copy(DateStr,12,2),0); Sec := StrToIntDef(Copy(DateStr,14,2),0); end else begin Year := StrToIntDef(Copy(DateStr,1,4),1900); Month := StrToIntDef(Copy(DateStr,5,2),1); Day := StrToIntDef(Copy(DateStr,7,2),1); Hour := StrToIntDef(Copy(DateStr,9,2),0); Min := StrToIntDef(Copy(DateStr,11,2),0); Sec := StrToIntDef(Copy(DateStr,13,2),0); end; result := UTCToSystemTime(EncodeDate(Year, Month, Day) + EncodeTime(Hour, Min, Sec, 0)); end else result := 0; except result := 0; end; end;