xref: /original-bsd/usr.bin/w/pr_time.c (revision c8089215)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)pr_time.c	5.2 (Berkeley) 08/30/90";
10 #endif /* not lint */
11 
12 #include <sys/types.h>
13 #include <sys/time.h>
14 #include <stdio.h>
15 #include <string.h>
16 
17 #define	HR	(60 * 60)
18 #define	DAY	(24 * HR)
19 #define	MON	(30 * DAY)
20 
21 static time_t now;
22 /*
23  * prttime prints a time in hours and minutes or minutes and seconds.
24  * The character string tail is printed at the end, obvious
25  * strings to pass are "", " ", or "am".
26  */
27 static char *
28 prttime(tim, tail)
29 	time_t tim;
30 	char *tail;
31 {
32 	int mins;
33 	static char timebuf[32];
34 
35 	if (tim >= 60) {
36 		mins = tim % 60;
37 		(void) sprintf(timebuf, "%2d:%02d%s", (int)(tim / 60), mins,
38 		    tail);
39 	} else if (tim >= 0)
40 		(void) sprintf(timebuf, "    %2d%s", (int)tim, tail);
41 	else
42 		(void) strcpy(timebuf, tail);
43 
44 	return (timebuf);
45 }
46 
47 static char *weekday[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
48 static char *month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
49 		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
50 
51 /* prtat prints a 12 hour time given a pointer to a time of day */
52 char *
53 attime(started)
54 	time_t *started;
55 {
56 	struct tm *p;
57 	register int hr, pm;
58 	static char prbuff[64];
59 
60 	if (now == 0)
61 		(void) time(&now);
62 	p = localtime(started);
63 	hr = p->tm_hour;
64 	pm = (hr > 11);
65 	if (hr > 11)
66 		hr -= 12;
67 	if (hr == 0)
68 		hr = 12;
69 	if (now - *started <= 18 * HR)
70 		return (prttime((time_t)hr * 60 + p->tm_min, pm ? "pm" : "am"));
71 	if (now - *started <= 7 * DAY)
72 		(void) sprintf(prbuff, "%*s%d%s", hr < 10 ? 4 : 3,
73 			weekday[p->tm_wday], hr, pm ? "pm" : "am");
74 	else
75 		(void) sprintf(prbuff, "%2d%s%2d", p->tm_mday,
76 			month[p->tm_mon], p->tm_year);
77 
78 	return (prbuff);
79 }
80