• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2597
  • Last Modified:

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
0
Jing272
Asked:
Jing272
  • 2
  • 2
1 Solution
 
SreejithGCommented:
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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now