views:

194

answers:

4

I tried strftime( ) to get a formatted time-stamp.

char ft[ 256 ];
struct tm *tmp;
strftime( ft, 256, "%D - %T", tmp );

My problem is that I get "13/02/60 - 03:07:-17958194" as a result. Is there a way to display the seconds properly? (I'm using Mac OS X and gcc)

+6  A: 

You're using an uninitialized value in the code that you've posted, which would explain why you have this problem. The following code results in what you're looking for:

#include <stdio.h>
#include <time.h>

int
main(int argc, char *argv[]) {
  char ft[256];
  struct tm *tmp;
  time_t curtime;

  time(&curtime);
  tmp = localtime(&curtime);

  strftime(ft, 256, "%D - %T %s", tmp);
  printf("%s\n", ft);

  return(0);
}

Then, compile and run the example:

cc -o time_ex time_ex.c
./time_ex
02/26/09 - 11:26:34 1235665594

ETA: Drop the %s if you just want the local time without UNIX time after it, of course.

Michael Trausch
A: 

You aren't initialising struct tm *tmp; with anything - please could you post a complete example?

Douglas Leeder
This was the complete example, I didn't know how to initialize it.
Nino
+3  A: 

"%D - %T" should give you proper results, assuming you want "mm/dd/yy - hh:mm:ss".

If your example is accurate to your usage, you may want to consider giving the function a real time instead of some random address in memory.

Ryan Graham
+1  A: 

%s and %S are different formatting characters.

  • %s is the number of seconds since the unix epoch.
  • %S is the current time's seconds value (00-60) with a leading 0 for numbers < 10.
R. Bemrose
Hah, wow. I need to change my monospace font. At a glance in my current font, lower-s and upper-s are nearly indistinguishable. Meh. I didn't think to look again until you posted this. Thank you, though.
Michael Trausch