SAS date subtraction when intck function doesn't cut it

598 views Asked by At

I need to do some date subtraction in my SAS code, but I don't think the INTCK function will work because I would like the answer to present the difference in days:hours:minutes. I could program this out, but I am guessing there is probably a format or function I'm not aware of to accomplish the task.

For example:

Date1 = 01JAN2000 12:00

Date2 = 02JAN2000 14:30

difference = 1:02:30 (i.e. 1 day, 2 hours, 30 minutes)

In this case, if I used INTCK I would need to keep the units in either days or hours, but I can't get the desired format above.

1

There are 1 answers

5
Tom On BEST ANSWER

You should be able to use the %n directive in a PICTURE format.

proc format;
 picture pictdhmf
  low-high='%0n:%0H:%0M'(datatype=time)
 ;
run;

Note you need to use data type of TIME. WARNING: It doesn't produce proper results when running SAS using DBCS support (for example using Shift-JIS encoding). Or for times that are less than zero. It does work for non-negative values when using single byte character sets, even with UTF-8 encoding.

So instead you could build a function.

proc fcmp outlib=work.func.func;
function dhmf(c) $;
  length f $ 10;
  f=catx(':',datepart(abs(c)),put(timepart(abs(c)),tod5.));
  if c < 0 then f='-'||f ;
  return (f);
endsub;
run;
options cmplib=work.func;

and then make a format that calls the function.

proc format;
value dhmf(default=10)
 other=[dhmf()];
run;

So if we test both methods and compare to the values that TIME format produces.

data _null_;
  input (date1 date2) (:datetime24.) ;
  diff = date2 - date1 ;
  if _n_=1 then put 'RAW' @11 'TIME.' @20 'Function' @ 30 'Picture';
  put diff comma9. @11 diff time. @20 diff dhmf. @30 diff pictdhmf.-l ;
cards ;
01JAN2000:02:30 02JAN2000:03:45
01JAN1960:08:00 01JAN1960:17:00
01FEB2017:00:00 04FEB2017:06:23
01FEB2015:00:00 04FEB2017:06:23
04FEB2017:00:00 01FEB2017:06:23
run;

We get:

 RAW       TIME.    Function  Picture
    90,900 25:15:00 1:01:15   1:01:15    
    32,400  9:00:00 0:09:00   0:09:00    
   282,180 78:23:00 3:06:23   3:06:23    
  63440580 17622:23 734:06:23 734:06:23  
  -236,220   -65:37 -2:17:37  -2:06:23