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