Search code examples
cdatetimestrftime

Debug assertion failure while using strftime


My code is below,

time_t t;
struct tm tm;
struct tm * tmp;
time( &t ); 
tmp = gmtime(&t);

char buf[100];
strftime(buf, 42, "%F", tmp); // assertion failure

It says `expression:("Invalid format directive",0). I wanted to convert the time to Short YYYY-MM-DD date, equivalent to %Y-%m-%d format.

Same thing happens when I try this,

const char* fmt = "%a, %d %b %y %T %z";

if (strftime(buf, sizeof(buf), fmt, tmp) == 0) // assertion failure
{ 
    fprintf(stderr, "strftime returned 0");
    exit(EXIT_FAILURE); 
} 

Solution

  • %F, %T and %z were introduced by C99, and only came to C++ in C++11. From the comments on your question, it appears you're using Microsoft's partial implementation of C++11 in VisualStudio 2010. Unfortunately your only options are:

    • update your IDE (I don't know if later versions support this, but I'd imagine they do)
    • switch to a different IDE (anything which uses GCC for its compiler will certainly support this)
    • avoid using the newer formatting flags (you can find a list here: http://www.cplusplus.com/reference/ctime/strftime/ anything yellow is new)