代码之家  ›  专栏  ›  技术社区  ›  Cheeso

如何从C代码(win32)生成RFC1123日期字符串

  •  5
  • Cheeso  · 技术社区  · 15 年前

    RFC1123 定义了许多东西,其中包括要在Internet协议中使用的日期格式。HTTP协议 RFC2616 )指定必须根据RFC1123生成日期格式。

    看起来是这样的:

    Date: Wed, 28 Apr 2010 02:31:05 GMT
    

    如何从运行在Windows上的C代码生成RFC1123时间字符串? 我没有使用c和datetime.tostring()。

    我知道我可以自己编写代码,发出时区和日期缩写,但我希望这已经存在于windows api中。

    谢谢。

    5 回复  |  直到 11 年前
        1
  •  9
  •   Cheeso    15 年前

    这是我用过的:

    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;
    }
    
        2
  •  2
  •   Jerry Coffin    15 年前

    这是未经测试的,但应该相当接近:

    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);
    
        3
  •  2
  •   YOU    15 年前

    可能, InternetTimeFromSystemTime 从wininet api。

    使用RFC格式。目前,唯一 有效格式为 互联网格式。

        4
  •  1
  •   Ernest Poletaev    12 年前

    更普遍的例子

    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;
    }
    
        5
  •  0
  •   wick    11 年前

    我用过这个:

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

    实际上,我使用CTime_r call是为了线程安全,但不管哪种方式都有效…