Hi all,

why is the following code printing the wrong result?

/*
 Returns the current time.
*/
char *time_stamp(){

	char *str = (char *)malloc(sizeof(char) * 23);
	int len;
	struct timeval tv;
	struct timezone tz;
	struct tm *tm;
	
	gettimeofday(&tv, &tz);
	tm=localtime(&tv.tv_sec);


		
	printf("\n\n\n%04d-%02d-%02d %d:%02d:%02d:%03d\n\n\n", tm->tm_year, tm->tm_mon, 
		tm->tm_wday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec/1000);


	sprintf(str, "%04d-%02d-%02d %d:%02d:%02d:%03d", tm->tm_year, tm->tm_mon, 
		tm->tm_wday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec/1000);
	return str;
}

it is printing the time right, but not the date.
it should be printing 2010-09-01 <time>...

but it is printing 0110-08-03

You're getting a timeval structure back. You need to do a little formatting before you can use it.

Here are some highlights from the man page... http://linux.die.net/man/3/localtime

  • tm_year is the number of years since 1900... so add 1900 to your tm_year result.
  • tm_mon is the month where January is month number 0... so add 1 to your month.
  • tm_wday counts the number of days since Sunday... so you need to figure out how to get the day of the year yourself. You may want to use tm_yday which returns the day of the year (0 being January first).

I hope this helps you get started. Read that link carefully to find out more about the function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.