我正在执行以下操作以获取“日月日年”格式的时间。
struct tm *example= localtime(&t);
strftime(buf,sizeof(buf),"%a %b %d %Y",example);
strncpy(time_buffer,buffer,sizeof(time_buffer)) ;
但是,如果日期是个位数,例如 9,则显示为 9。我想将其打印为 09。知道怎么做吗?
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;
}