Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the default local time format in C++?

Tags:

c++

time

I have a function:

string get_current_time()
{
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    return asctime (timeinfo);
}

which returns time in the following format:

Fri Mar 18 11:25:04 2011

How do I change it so that it is returned in the following format?

2011 03-18 11-25-04 Fri

I want to use this for log file names.

like image 333
NullVoxPopuli Avatar asked Mar 18 '11 15:03

NullVoxPopuli


1 Answers

As @0A0D suggested, whilst you can't change asctime, you can use strftime to format the data contained in your time_t:

string get_current_time()
{
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    char output[30];
    strftime(output, 30, "%Y %m-%d %H-%M-%S %a", timeinfo);

    return string(output);
}

(I've also dropped a copy on to IdeOne here.)

like image 56
razlebe Avatar answered Oct 15 '22 03:10

razlebe