如何解析UTC日期?

时间:2013-12-26 05:08:20

标签: delphi delphi-7 delphi-6

我需要使用 Delphi 6

解析UTC日期
2013-12-24T11:05:01.000+09:00

Delphi 7 中,我设法使用以下代码执行此操作:

  1. 使用TXsDateTime

    var
     utcTime : TXsDateTime;
     localTime : TDateTime;
     temp : string;
    begin
     temp := '2013-12-24T00:00:00.000-02:00';
     utcTime.XSToNative(temp);
     localTime := utcTime.AsUTCDateTime; // get time in +00:00 timezone
     localTime := IncHour(localTime, 9); // het time local timezone
     //...
    end;
    
  2. StrToDateTime使用TFormatSettings重载:

    var
      localTime : TDateTime;
      temp, datetimePart : string;
      formatSettings : TFormatSettings;
    begin
     temp := '2013-12-24T00:00:00.000+01:00';
     //init format settings
     GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, formatSettings);
     formatSettings.DateSeparator := '-';
     formatSettings.ShortDateFormat := 'yyyy-MM-dd';
     //parse datetime
     datetimePart := StringReplace(copy(temp,1,Length(temp)-10),'T',' ',[]);
     localTime := StrToDateTime(datetimePart, formatSettings);
     //get datetime in +00:00 timezone
     localTime := IncHour(localTime, -1*strtoint(copy(temp,Length(temp)-5,3)));
     localTime := IncMinute(localTime, -1*strtoint(copy(temp,Length(temp)-1,2)));
     //get datetime in local timezone
     localTime := IncHour(localTime , 9);
     //...
    end;
    
  3. 但是在Delphi 6中:

    1. 我甚至无法拨打XSToNative,因为它会导致EConvertError错误地放置日期的月份和日期部分;并且TXsDateTime不包含AsUTCDateTime ...
    2. 的定义
    3. SysUtils不包含TFormatSettings的定义,因此我使用的StrToDateTime的重载不可用。
    4. 我有什么遗漏,或者我可以用什么来解析 Delphi 6 中的这种格式?

1 个答案:

答案 0 :(得分:1)

最后我使用了EncodeDateTime函数:

var
 time1, time2 : TDateTime;
 year,month,day,hour,minute,second,mlsecond, hourOffset, minOffset : integer;
 temp :string;
begin
 temp := '2013-12-24T00:00:00.000-09:30';
 //parse separate parts of the datetime
 year := strtoint(copy(temp,1,4));
 month := strtoint(copy(temp,6,2));
 day := strtoint(copy(temp,9,2));
 hour := strtoint(copy(temp,12,2));
 minute := strtoint(copy(temp,15,2));
 second := strtoint(copy(temp,18,2));
 mlsecond := strtoint(copy(temp,21,3));
 hourOffset := strtoint(copy(temp,25,2));
 minOffset := strtoint(copy(temp,28,2));
 //adjust timezone offset sign
 if(temp[24]='+')then
 begin
  hourOffset := -1 * hourOffset;
  minOffset := -1 * minOffset;
 end;
 //get time in the +00:00 timezone
 time1 := EncodeDateTime(year,month,day,hour,minute,second,mlsecond);
 time1 := IncHour(time1, hourOffset);
 time1 := IncMinute(time1, minOffset);
 //get time in local timezone
 time2 := IncHour(time1, 9);
 //...
end;