How to change the default local time format in C ++?

I have a function:

string get_current_time() { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); return asctime (timeinfo); } 

which returns the time in the following format:

 Fri Mar 18 11:25:04 2011 

How can I change it so that it returns in the following format?

 2011 03-18 11-25-04 Fri 

I want to use this for log file names.

+4
source share
2 answers

Like @ 0A0D , but you cannot 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 also threw a copy on IdeOne here .)

+5
source

asctime() always returned in the format Www Mmm dd hh: mm: ss yyyy. It cannot be changed.

If you want to use a different format, see the strftime () .

+3
source

Source: https://habr.com/ru/post/1344291/


All Articles