分類: DELPHI |
我想實現 2007-08-13 12:00:00 與45 的結果變爲 2007-08-13 12:45:00
delhpi中日期型數據是能夠直接相加減的。
若是是字符串,用StrToDateTime轉成TDateTime類型,再相加,加完以後在用DateTimeToStr轉回去
日期是一個Double類型的浮點數,年月日是它的整型部分,時分秒是它的小數部分。
var
a:TDateTime;
begin
a:=StrToDateTime('2007-08-13 12:00:00');
a:=a + 45*(1/24/60);//一天等於24小時,一小時60分鐘
ShowMessage(FormatDateTime('yyyy-mm-dd hh:nn:ss',a));
end;html
同理,若是要加多少天,你就直接a := a + N 便可,整數部分就是天。
Delphi中日期時間型就是Float型,操做能夠和Float同樣。整數是以天爲單位的,小數部分算法就是 1小時=1/24;1小時X分就是 1/24 + (1/24)/60*x。其它的本身算吧
DateUtils.pas中有相關的函數:
function IncDay(const AValue: TDateTime;
const ANumberOfDays: Integer): TDateTime;
begin
Result := AValue + ANumberOfDays;
end;算法
function IncHour(const AValue: TDateTime;
const ANumberOfHours: Int64): TDateTime;
begin
Result := ((AValue * HoursPerDay) + ANumberOfHours) / HoursPerDay;
end;函數
function IncMinute(const AValue: TDateTime;
const ANumberOfMinutes: Int64): TDateTime;
begin
Result := ((AValue * MinsPerDay) + ANumberOfMinutes) / MinsPerDay;
end;spa
function IncSecond(const AValue: TDateTime;
const ANumberOfSeconds: Int64): TDateTime;
begin
Result := ((AValue * SecsPerDay) + ANumberOfSeconds) / SecsPerDay;
end;orm
function IncMilliSecond(const AValue: TDateTime;
const ANumberOfMilliSeconds: Int64): TDateTime;
begin
Result := ((AValue * MSecsPerDay) + ANumberOfMilliSeconds) / MSecsPerDay;
end;
把秒換算整天,而後相加獲得的就是你要的結果了。
謝謝你們了,我本身琢磨了如下,想法和crazycock一樣.[:D][:D]
Delphi裏有現成的函數能夠實現日期加減,是在DateUtils單元裏的。
function IncYear(const AValue: TDateTime;
const ANumberOfYears: Integer = 1): TDateTime;
// function IncMonth is in SysUtils
function IncWeek(const AValue: TDateTime;
const ANumberOfWeeks: Integer = 1): TDateTime;
function IncDay(const AValue: TDateTime;
const ANumberOfDays: Integer = 1): TDateTime;
function IncHour(const AValue: TDateTime;
const ANumberOfHours: Int64 = 1): TDateTime;
function IncMinute(const AValue: TDateTime;
const ANumberOfMinutes: Int64 = 1): TDateTime;
function IncSecond(const AValue: TDateTime;
const ANumberOfSeconds: Int64 = 1): TDateTime;
function IncMilliSecond(const AValue: TDateTime;
const ANumberOfMilliSeconds: Int64 = 1): TDateTime;
htm