How to get local time in format yyyyMMddHHmmss?

Hi, could you help me to get local time in string formating like yyyyMMddHHmmss? I know this:

        time_t rawtime;
        struct tm * timeinfo;
        time(&rawtime );
        timeinfo = localtime ( &rawtime );
        printf ( "Current local time and date: %s", asctime (timeinfo) );

But Output:
Current local time and date: Tue Nov 11 15:28:15 2008
Jing272Asked:
Who is Participating?
 
SreejithGConnect With a Mentor Commented:
Using sprintf , you can get the required format. Sample code below
	    time_t rawtime;
        struct tm * timeinfo;
        time(&rawtime );
        timeinfo = localtime ( &rawtime );
        printf ( "Current local time and date: %s", asctime (timeinfo) );
		char timeformat1[50]; // YYYY/MM/DD HH:MM:SS
		sprintf(timeformat1, "%04d/%02d/%2d %02d:%02d:%02d", (1900+timeinfo->tm_year), (timeinfo->tm_mon+1), timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min,timeinfo->tm_sec);
		printf("\nTime in format 1 %s",timeformat1);
 
		char timeformat2[50]; // YYYYMMDDHHMMSS
		sprintf(timeformat2, "%04d%02d%2d%02d%02d%02d", (1900+timeinfo->tm_year), (timeinfo->tm_mon+1), timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min,timeinfo->tm_sec);
		printf("\nTime in format 1 %s",timeformat2);

Open in new window

0
 
Jing272Author Commented:
They are working excellent. Thanks a lot.
0
 
Infinity08Commented:
Why not use strftime ? It's made for just this purpose :

        http://www.cplusplus.com/reference/clibrary/ctime/strftime.html

sprintf is overly complicated and unnecessary in this case.
char timestamp[64] = "";
strftime(buffer, 64, "Current local time and date: %Y%m%d%H%M%S", timeinfo);

Open in new window

0
 
Jing272Author Commented:
It is better and simple. Thanks.
0
 
Infinity08Commented:
Note that the 'buffer' had to be 'timestamp' in my code example obviously :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.