2013-08-24 10 views
5

ls Befehl druckt Zeit in diesem Format:Wie kann time_t in einem bestimmten Format gedruckt werden?

Aug 23 06:07 

Wie kann ich Zeit konvertieren von stat() ‚s mtime() in dieses Format für die lokale Zeit empfangen?

+0

analog für 'clock_t' : http://stackoverflow.com/questions/1083142/what-s-the-correct-way-to-use-printf-to-prin t-a-clock-t –

Antwort

11

Verwenden strftime (müssen Sie time_t-struct tm* zuerst konvertieren):

char buff[20]; 
struct tm * timeinfo; 
timeinfo = localtime (&mtime); 
strftime(buff, sizeof(buff), "%b %d %H:%M", timeinfo); 

Formate:

%b - The abbreviated month name according to the current locale. 

%d - The day of the month as a decimal number (range 01 to 31). 

%H - The hour as a decimal number using a 24-hour clock (range 00 to 23). 

%M - The minute as a decimal number (range 00 to 59). 

Hier wird der vollständige Code ist:

struct stat info; 
char buff[20]; 
struct tm * timeinfo; 

stat(workingFile, &info); 

timeinfo = localtime (&(info.st_mtime)); 
strftime(buff, 20, "%b %d %H:%M", timeinfo); 
printf("%s",buff); 
+0

und dann 'printf ("% s ", buff);'? – kBisla

+0

Genau - es füllt das 'buff' Array mit der druckbaren Zeichenkette. –

+0

bin nicht mit verschiedenen Zeitdatentypen vertraut. können Sie sagen, was die Schritte von stat() sein sollten – kBisla