8

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.

Angga
  • 95
  • 1
  • 1
  • 7

1 Answers1

10

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);
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • that two functions return the current time in a `tm` format. In this case, I had defined my own `time_t` to be converted into `tm`. – Angga Jan 14 '14 at 05:58
  • @Angga, those two functions have nothing to do with the current time. They will work on an arbitrary `time_t` value, either current time from `time(0)` or any other point in time like `(time_t)42`. – paxdiablo Jan 14 '14 at 06:15
  • I've tried it but localtime() need const time_t *, while my variable is using time_t data type. I tried to cast it, or using localtime(&myvar) it made my program error. any solution? – Angga Jan 19 '14 at 02:32
  • Yes, post your error and let us have look, preferably in a new question since 1/ it's only tangentially related to this one and 2/ you'll get a broader respone than if you simply ask in a comment. – paxdiablo Jan 19 '14 at 11:30
  • thank you so much for your help. after some editing, it's working now. – Angga Jan 21 '14 at 09:51