开发者

generate a date string in HTTP response date format in C

开发者 https://www.devze.com 2023-04-07 17:37 出处:网络
I\'m trying to generate a date string from current time to put into HTTP response header. It looks like this:

I'm trying to generate a date string from current time to put into HTTP response header. It looks like this:

Date: Tue, 15 Nov 2010 08:12:31 GMT

I only have the default C library to work with. How 开发者_开发百科do I do this?


Use strftime(), declared in <time.h>.

#include <stdio.h>
#include <time.h>

int main(void) {
  char buf[1000];
  time_t now = time(0);
  struct tm tm = *gmtime(&now);
  strftime(buf, sizeof buf, "%a, %d %b %Y %H:%M:%S %Z", &tm);
  printf("Time is: [%s]\n", buf);
  return 0;
}

See the code "running" at codepad.


Another solution is to avoid strftime() as it is impacted by locales and write your own function:

void http_response_date(char *buf, size_t buf_len, struct tm *tm)
{
    const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct", "Nov", "Dec"};

    snprintf(buf, buf_len, "%s, %d %s %d %02d:%02d:%02d GMT",
        days[tm->tm_wday], tm->tm_mday, months[tm->tm_mon],
        tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec);
}

int http_response_date_now(char *buf, size_t buf_len)
{
    time_t now = time(NULL);
    if (now == -1)
        return -1;

    struct tm *tm = gmtime(&now);
    if (tm == NULL)
        return -1;

    http_response_date(buf, buf_len, tm);
    return 0;
}

Example output as of the time of writing: Tue, 20 Oct 2020 22:28:01 GMT. The output length will be 28 or 29 (if the month day >= 10), so a 30 char buffer is enough.


Check if your platform has strftime : http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html .


Use gmtime(3) + mktime(3). You will end up with a struct tm that has all that information.

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};
0

精彩评论

暂无评论...
验证码 换一张
取 消