C - How to convert time_t to tm?

Angga picture Angga · Jan 14, 2014 · Viewed 12k times · Source

I have a variable which using time_t data type. I want to convert this type into "YYYY-MM-DD HH:MM:SS". I just know if it's only works in localtime() example:

char buff[20];
time_t now = time(NULL);
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));

any suggestion how to convert it? because I have the time which always increased every minute, not the fixed one like the localtime(). I need this conversion for matching with datetime type in MySQL database.

Answer

paxdiablo picture paxdiablo · Jan 14, 2014

The functions gmtime and localtime (for UTC and local time respectively) will turn an arbitrary time_t into a struct tm with individual fields for year, month and so on.

You can then just use strftime as you have, or sprintf to create strings from them, such as with:

char buff[11];
sprintf (buff, "%04d-%02d-%02d",
    mytm.tm_year + 1900,
    mytm.tm_mon + 1,
    mytm.tm_mday);