在C中以HTTP响应日期格式生成日期字符串

时间:2011-09-25 21:30:18

标签: c date

我正在尝试从当前时间生成日期字符串以放入HTTP响应标头。它看起来像这样:

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

我只有默认的C库可供使用。我该怎么做?

4 个答案:

答案 0 :(得分:19)

使用<time.h>中声明的strftime()

#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;
}

请参阅code "running" at codepad

答案 1 :(得分:0)

使用gmtime(3)+ mktime(3)。 最终会得到一个包含所有信息的struct tm。

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 */
};

答案 2 :(得分:0)

检查您的平台是否有strftimehttp://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html

答案 3 :(得分:0)

另一种解决方案是避免strftime()受到语言环境的影响,并编写自己的函数:

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;
}

截至撰写本文时的示例输出:Tue, 20 Oct 2020 22:28:01 GMT。输出长度将为28或29(如果月日> = 10),那么30个字符的缓冲区就足够了。