date_diff.m 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function out = date_diff(date1, date2, interval)
  2. % out = date_diff(date1, date2, interval)
  3. % Inputs
  4. % date1 a date in yyyy-mm-dd or yyyy-mm-dd hh:mm:ss format
  5. % date2 a date in yyyy-mm-dd or yyyy-mm-dd hh:mm:ss format
  6. % interval one of 'year','day','hour','minute','second'
  7. %
  8. % Note: date1 and date2 can either be date character arrays or cell
  9. % arrays (must be same size or only one should be a cell array)
  10. % if they are both arrays the diff is taken element-wise. if only one is an
  11. % array then the scalar date is compared to all elements of the array.
  12. %
  13. % Output
  14. % The time passed from date2 to date1 in units of interval
  15. if iscell(date1) && iscell(date2) % two cell arrays
  16. assert(isequal(size(date1),size(date2)),'date1 and date2 must have same size');
  17. out = cellfun(@(x,y)date_diff_int(x,y,interval),date1,date2);
  18. elseif iscell(date1) % date1 is a cell
  19. assert(ischar(date2),'If date2 is not a cell array it must be a char');
  20. out = cellfun(@(x)date_diff_int(x,date2,interval),date1);
  21. elseif iscell(date2) % date2 is a cell
  22. assert(ischar(date1),'If date1 is not a cell array it must be a char');
  23. out = cellfun(@(x)date_diff_int(date1,x,interval),date2);
  24. else
  25. out = date_diff_int(date1,date2,interval);
  26. end
  27. end
  28. function out = date_diff_int(date1,date2,interval)
  29. out_in_days = datenum(date1) - datenum(date2);
  30. switch lower(interval(1:2)) % I only take the first 2 char to allow for plural.
  31. case 'ye' %years
  32. out = out_in_days / 365;
  33. case 'da' %days
  34. out = out_in_days;
  35. case 'ho' %hours
  36. out = out_in_days*24;
  37. case 'mi' %minutes
  38. out = out_in_days*24*60;
  39. case 'se' %seconds
  40. out = out_in_days*24*60*60;
  41. otherwise
  42. error('utils:date_diff','Do not know about interval %s',interval);
  43. end
  44. end