DateAddDay on steroid << Back



Read this previous post on leap year bug first. I thought I had come up with a decent solution, but Oliver pointed out that my solution can't add more than 65535 days. While I have never had the need to add that many days to a datetime variable, he is right none-the-less. Let me come up with a solution that is a bit more robust.


Function DateAddDay Global DateTime dtVar Integer iAdd Returns DateTime
    DateTime dtVar2
    Variant vt
    Real r
    Boolean bOK
    Integer iHour iMin iSec iMilliSec
    If (IsNullDateTime(dtVar) or not(IsDateValid(dtVar))) Begin
        Error DFERR_INVALID_DATETIME
        Function_Return dtVar2
    End
    
    Move (DateGetHour(dtVar)) to iHour
    Move (DateGetMinute(dtVar)) to iMin
    Move (DateGetSecond(dtVar)) to iSec
    Move (DateGetMilliSecond(dtVar)) to iMilliSec
    Move (Date(dtVar)) to vt // Cheap trick to blank out the time portion
    
	Move 0 to r
    Move (MemCopy(AddressOf(r), AddressOf(vt) + 8, 8)) to bOK
    Move (r + Real(iAdd)) to r
    Move (MemCopy(AddressOf(vt) + 8, AddressOf(r), 8)) to bOK
    
    Move vt to dtVar
    Move (DateSetHour(dtVar, iHour)) to dtVar
    Move (DateSetMinute(dtVar, iMin)) to dtVar
    Move (DateSetSecond(dtVar, iSec)) to dtVar
    Function_Return (DateSetMilliSecond(dtVar, iMilliSec))
End_Function

Go read the previous articles here and here if any part of the code confuses you.






Free Web Hosting