1 # include <ctype.h> 2 # include "useful.h" 3 4 SCCSID(@(#)convtime.c 3.3 11/28/82); 5 6 /* 7 ** CONVTIME -- convert time 8 ** 9 ** Takes a time as an ascii string with a trailing character 10 ** giving units: 11 ** s -- seconds 12 ** m -- minutes 13 ** h -- hours 14 ** d -- days (default) 15 ** w -- weeks 16 ** For example, "3d12h" is three and a half days. 17 ** 18 ** Parameters: 19 ** p -- pointer to ascii time. 20 ** 21 ** Returns: 22 ** time in seconds. 23 ** 24 ** Side Effects: 25 ** none. 26 */ 27 28 time_t 29 convtime(p) 30 char *p; 31 { 32 register time_t t, r; 33 34 r = 0; 35 while (*p != '\0') 36 { 37 t = 0; 38 while (isdigit(*p)) 39 t = t * 10 + (*p++ - '0'); 40 switch (*p++) 41 { 42 case 'w': /* weeks */ 43 t *= 7; 44 45 case '\0': 46 p--; 47 /* fall through... */ 48 49 case 'd': /* days */ 50 default: 51 t *= 24; 52 53 case 'h': /* hours */ 54 t *= 60; 55 56 case 'm': /* minutes */ 57 t *= 60; 58 59 case 's': /* seconds */ 60 break; 61 } 62 r += t; 63 } 64 65 return (r); 66 } 67 /* 68 ** PINTVL -- produce printable version of a time interval 69 ** 70 ** Parameters: 71 ** intvl -- the interval to be converted 72 ** brief -- if TRUE, print this in an extremely compact form 73 ** (basically used for logging). 74 ** 75 ** Returns: 76 ** A pointer to a string version of intvl suitable for 77 ** printing or framing. 78 ** 79 ** Side Effects: 80 ** none. 81 ** 82 ** Warning: 83 ** The string returned is in a static buffer. 84 */ 85 86 # define PLURAL(n) ((n) == 1 ? "" : "s") 87 88 char * 89 pintvl(intvl, brief) 90 time_t intvl; 91 bool brief; 92 { 93 static char buf[256]; 94 register char *p; 95 int wk, dy, hr, mi, se; 96 97 if (intvl == 0 && !brief) 98 return ("zero seconds"); 99 100 /* decode the interval into weeks, days, hours, minutes, seconds */ 101 se = intvl % 60; 102 intvl /= 60; 103 mi = intvl % 60; 104 intvl /= 60; 105 hr = intvl % 24; 106 intvl /= 24; 107 if (brief) 108 dy = intvl; 109 else 110 { 111 dy = intvl % 7; 112 intvl /= 7; 113 wk = intvl; 114 } 115 116 /* now turn it into a sexy form */ 117 p = buf; 118 if (brief) 119 { 120 if (dy > 0) 121 { 122 (void) sprintf(p, "%d+", dy); 123 p += strlen(p); 124 } 125 (void) sprintf(p, "%02d:%02d:%02d", hr, mi, se); 126 return (buf); 127 } 128 129 /* use the verbose form */ 130 if (wk > 0) 131 { 132 (void) sprintf(p, ", %d week%s", wk, PLURAL(wk)); 133 p += strlen(p); 134 } 135 if (dy > 0) 136 { 137 (void) sprintf(p, ", %d day%s", dy, PLURAL(dy)); 138 p += strlen(p); 139 } 140 if (hr > 0) 141 { 142 (void) sprintf(p, ", %d hour%s", hr, PLURAL(hr)); 143 p += strlen(p); 144 } 145 if (mi > 0) 146 { 147 (void) sprintf(p, ", %d minute%s", mi, PLURAL(mi)); 148 p += strlen(p); 149 } 150 if (se > 0) 151 { 152 (void) sprintf(p, ", %d second%s", se, PLURAL(se)); 153 p += strlen(p); 154 } 155 156 return (buf + 2); 157 } 158