我正在执行以下操作以获得“日月日”格式的时间。
struct tm *example= localtime(&t);
strftime(buf,sizeof(buf),"%a %b %d %Y",example);
strncpy(time_buffer,buffer,sizeof(time_buffer)) ;
但是如果日期是单个数字,例如9,则显示为9.我想将其打印为09.任何想法如何做到?
答案 0 :(得分:1)
strftime的联机帮助页说:
%d The day of the month as a decimal number (range 01 to 31).
这似乎是你想要的。
// compile with: gcc -o ex1 -Wall ex1.c
#include "stdio.h"
#include "sys/time.h"
#include "time.h"
int main (const int argc, const char ** argv ) {
time_t curr_time;
char buff[1024];
// time(&curr_time);
curr_time = 1359684105; // Thu Jan 31 2013
struct tm *now = localtime(&curr_time);
strftime(buff, sizeof(buff), "%a %b %d %Y", now);
printf("time: %ld\n", curr_time);
printf("time: %s\n", buff);
curr_time += 24 * 60 * 60; // Fri Feb 01 2013
now = localtime(&curr_time);
strftime(buff, sizeof(buff), "%a %b %d %Y", now);
printf("time: %ld\n", curr_time);
printf("time: %s\n", buff);
return 0;
}
产生:
time: 1359684105
time: Thu Jan 31 2013
time: 1359770505
time: Fri Feb 01 2013
看起来就像你追求的那样。如果要删除前导零,可以使用%e:
%e Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. (SU)
作者报告%d不遵守solaris上的联机帮助页,这是另一种直接使用sprintf的解决方案:
// compile with: gcc -o ex1 -Wall ex1.c
#include "stdio.h"
#include "sys/time.h"
#include "time.h"
int main (const int argc, const char ** argv ) {
time_t curr_time;
char buff[1024], daynamebuff[8], monbuff[8], daynumbuff[3], yearbuff[8];
// time(&curr_time);
curr_time = 1359684105; // Thu Jan 31 2013
curr_time += 24 * 60 * 60; // Fri Feb 01 2013
struct tm *now = localtime(&curr_time);
strftime(daynamebuff, sizeof(daynamebuff), "%a", now);
strftime(monbuff, sizeof(monbuff), "%b", now);
strftime(daynumbuff, sizeof(daynumbuff), "%e", now);
strftime(yearbuff, sizeof(yearbuff), "%Y", now);
sprintf(buff, "%s %s %02d %s", daynamebuff, monbuff, now->tm_mday, yearbuff);
printf("%s\n", buff);
return 0;
}