Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - How to convert time_t to tm?

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.

like image 452
Angga Avatar asked Jan 14 '14 05:01

Angga


1 Answers

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);
like image 167
paxdiablo Avatar answered Sep 18 '22 06:09

paxdiablo