omega
omega

Reputation: 43863

how to get date and time in the format 2013-01-11 23:34:21?

In my C program, how can I get the date and time in the format 2013-01-11 23:34:21?

I tried

time_t now;
time(&now);
printf("%s", ctime(&now));

But it's giving it like Fri Jan 11 23:50:33 2013...

Thanks

Upvotes: 3

Views: 3415

Answers (2)

Masked Man
Masked Man

Reputation: 11045

You could use the strftime() function from <time.h>

#include <time.h>
#include <stdio.h>

int main() {
    time_t now;
    time(&now);

    struct tm* now_tm;
    now_tm = localtime(&now);

    char out[80];
    strftime (out, 80, "Now it's %Y-%m-%d %H:%M:%S.", now_tm);

    puts(out);
}

Output

Now it's 2013-01-12 10:33:13.

Upvotes: 5

nemo
nemo

Reputation: 57659

Try strftime from time.h:

char timeString[20];
time_t t;
struct tm tmp;

t = time(NULL);

// TODO: Error checking if (t < 0)

tmp = localtime_r(&t, &tmp);

// TODO: Error checking if tmp == NULL

strftime(timeString, sizeof(timeString), "%Y-%m-%d %H:%M:%S", tmp));

// TODO: Error checking if returned number == sizeof(timeString)-1

Upvotes: 2

Related Questions