Search code examples
cdate

generate a date string in HTTP response date format in C


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?


Solution

  • 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.