首页 > 解决方案 > 我在 C 中为日期使用什么格式说明符?

问题描述

这是我的代码(我知道使用 %d 是错误的,但我不确定我应该使用什么):

#include <stdio.h>
#include <stdlib.h>
int main()
{
char charactername[] = "Ruby";
int age =18;
printf("Once upon a time there was girl named %s\n",charactername);
printf("%s was %d years old\n",charactername,age);

age =19;
int birthday = 22/07/2003;

printf("on %d she was born\n",birthday);
printf("On 22/07/2022 she will become %d",age);

return 0;
}

这是终端给我的:

从前有一个女孩叫鲁比

鲁比 18 岁

在 0 她出生

2022 年 7 月 22 日,她将 19 岁

标签: cdateformat-specifiers

解决方案


您将使用struct tmstrftimefrom的组合time.h

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

int main( void )
{
  struct tm bdate = { .tm_year=(2003 - 1900), .tm_mday = 22, .tm_mon = 6 };
  char datebuf[11] = {0};
  
  strftime( datebuf, sizeof datebuf, "%d/%m/%Y", &bdate );
  printf( "bdate = %s\n", datebuf );
  return 0;
}

输出:

$ ./bdate
bdate = 22/07/2003

推荐阅读