668e8c052192827b1d015f03d46a6ce407d394e3
[citadel.git] / citadel / genstamp.c
1 /*
2  * Function to generate RFC822-compliant textual time/date stamp
3  */
4
5 #include "sysdep.h"
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <ctype.h>
9 #include <string.h>
10 #include <time.h>
11 #include "genstamp.h"
12
13
14 static char *months[] = {
15         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
16         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
17 };
18
19 static char *weekdays[] = {
20         "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
21 };
22
23
24 /*
25  * Supplied with a unix timestamp, generate an RFC822-compliant textual
26  * time and date stamp.
27  */
28 long datestring(char *buf, size_t n, time_t xtime, int which_format) {
29         struct tm t;
30
31         long offset;
32         char offsign;
33
34         localtime_r(&xtime, &t);
35
36         /* Convert "seconds west of GMT" to "hours/minutes offset" */
37 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
38         offset = t.tm_gmtoff;
39 #else
40         offset = timezone;
41 #endif
42         if (offset > 0) {
43                 offsign = '+';
44         }
45         else {
46                 offset = 0L - offset;
47                 offsign = '-';
48         }
49         offset = ( (offset / 3600) * 100 ) + ( offset % 60 );
50
51         switch(which_format) {
52
53                 case DATESTRING_RFC822:
54                         return snprintf(
55                                 buf, n,
56                                 "%s, %02d %s %04d %02d:%02d:%02d %c%04ld",
57                                 weekdays[t.tm_wday],
58                                 t.tm_mday,
59                                 months[t.tm_mon],
60                                 t.tm_year + 1900,
61                                 t.tm_hour,
62                                 t.tm_min,
63                                 t.tm_sec,
64                                 offsign, offset
65                                 );
66                 break;
67
68                 case DATESTRING_IMAP:
69                         return snprintf(
70                                 buf, n,
71                                 "%02d-%s-%04d %02d:%02d:%02d %c%04ld",
72                                 t.tm_mday,
73                                 months[t.tm_mon],
74                                 t.tm_year + 1900,
75                                 t.tm_hour,
76                                 t.tm_min,
77                                 t.tm_sec,
78                                 offsign, offset
79                                 );
80                 break;
81
82         }
83         return 0;
84 }