How can I generate an RFC1123 Date string, from C code (Win32)
RFC1123 defines a number of things, among them, the format of Dates to be used in internet protocols. HTTP (RFC2616) specifies that date formats must be generated in conformance with RFC1123.
It looks like this:
Date: Wed, 28 Apr 2010 02:31:05 GMT
How can I generate an RFC1123 time string from C code, running on Windows? I don't have the use of C# and DateTime.ToString().
I know I could write the code开发者_运维问答 myself, to emit timezones and day abbreviations, but I'm hoping this already exists in the Windows API.
Thanks.
This is what I used:
static const char *DAY_NAMES[] =
{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
static const char *MONTH_NAMES[] =
{ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
char *Rfc1123_DateTimeNow()
{
const int RFC1123_TIME_LEN = 29;
time_t t;
struct tm tm;
char * buf = malloc(RFC1123_TIME_LEN+1);
time(&t);
gmtime_s(&tm, &t);
strftime(buf, RFC1123_TIME_LEN+1, "---, %d --- %Y %H:%M:%S GMT", &tm);
memcpy(buf, DAY_NAMES[tm.tm_wday], 3);
memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
return buf;
}
This is untested, but should be reasonably close:
time_t t = time(NULL);
struct tm *my_tm = gmtime(&t);
strftime(buffer, buf_size, "%a, %d %b %Y %H:%M:%S GMT", my_tm);
puts(buffer);
Probably, InternetTimeFromSystemTime from Wininet API.
RFC format used. Currently, the only valid format is INTERNET_RFC1123_FORMAT.
More generalized example
std::string rfc1123_datetime( time_t time )
{
struct tm * timeinfo;
char buffer [80];
timeinfo = gmtime ( &time );
strftime (buffer,80,"%a, %d %b %Y %H:%M:%S GMT",timeinfo);
return buffer;
}
I used this:
char wd[4], mo[4], dn[3], tm[9], yr[5];
time_t now;
time(&now);
sscanf(ctime(&now), "%s %s %s %s %s", wd, mo, dn, tm, yr);
sprintf((char*) http_response, "\r\nDate: %s, %s %s %s %s GMTr\n\r\n", wd, dn, mo, yr, tm);
actually I used ctime_r call to be thread-safe, but it works either way...
精彩评论