Date/time comparisons

Hi,

Within a Cicode task (Citect 2016) I'm reading a date/time string from SQL which indicates when a backup job last ran (e.g. "2020-02-20 13:15:01") and need to determine if this date/time occurred within the last 15 minutes. I'm then raising an alarm if it didn't.

The solution (in Cicode) will no doubt be some combination of TimeCurrent(), DateSub() and TimeToStr(), but after a few attempts I'm not getting very far!

Could someone please provide some example Cicode of how best to do this comparison.

Thanks

Ash

  • Something like this:

    strDate = "2020-02-20";
    strTime = "13:15:01";
    IF (StrToDate(strDate) + StrToTime(strTime)) > (TimeCurrent() - StrToTime("00:15:00")) THEN
  • Hi Bas,
    Thanks for the reply. I'll give that a try.
  • Better to use DateSub() than subtracting the two time/date values to avoid issues during daylight saving time changes:

    sDT = "2020-02-20 13:15:01";
    iDT = StrToDate(StrLeft(sDT, 10)) + StrToTime(StrRight(sDT, 8));
    IF iDT > DateSub(TimeCurrent(), 15*60) THEN
    <raise alarm>
    END
  • Hi Ash,

    In general I recommend to use the Timestamp functions for time calculations.

    The Timestamp functions allow for a Timestamp value to be converted to or from a localised date/time string or a UTC date/time string.
    The Timestamp functions were specifically designed to facilitate precise date/time value calculations that are unaffected by daylight savings.

    Last the Time function will not work for dates beyond 2035, or before 1970.

    For your code :

    INT FUNCTION myTimeDifference(STRING sDTSQL ="2020-01-01 00:00:00", INT iMode=5)
    INT nYear,nMonth,nDay,nHour,nMin,nSec;
    TIMESTAMP tsSQL,tsCurrent;
    INT nDifference;

    INT bUTC = 1; //time from SQL is in UTC, important for timestampcreate. Any Timestamp is in UTC, so it needs to know on creation if the values provided are UTC

    nYear =StrToInt(StrMid(sDTSQL ,0,4));
    nMonth= StrToInt(StrMid(sDTSQL ,6,2));
    nDay=StrToInt(StrMid(sDTSQL ,8,2));
    nHour=StrToInt(StrMid(sDTSQL ,11,2));
    nMin=StrToInt(StrMid(sDTSQL ,14,2));
    nSec=StrToInt(StrMid(sDTSQL ,17,2));

    tsSQL = TimestampCreate(nYear,nMonth,nDay,nHour,nMin,nSec,0,bUTC);

    nDifference = TimestampDifference(TimestampCurrent(),tsSQL,iMode);

    TraceMsg("Timediff = "+nDifference:#);

    RETURN nDifference;

    END