我在 C 中为日期使用什么格式说明符?
What format specifier do I use in C for dates?
这是我的代码(我知道使用 %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;
}
这是终端给我的:
从前有个女孩叫Ruby
Ruby 18 岁
她出生于 0 日
2022 年 7 月 22 日她将年满 19 岁
C 中没有内置“日期”类型。您可以使用字符串作为任意文本;类似于:
const char *birthday = "22/07/2003";
你可以用 printf 格式的 %s
打印出来
printf("on %s she was born\n",birthday);
您将使用 time.h
中的 struct tm
and strftime
的组合:
#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
这是我的代码(我知道使用 %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;
}
这是终端给我的:
从前有个女孩叫Ruby
Ruby 18 岁
她出生于 0 日
2022 年 7 月 22 日她将年满 19 岁
C 中没有内置“日期”类型。您可以使用字符串作为任意文本;类似于:
const char *birthday = "22/07/2003";
你可以用 printf 格式的 %s
打印出来
printf("on %s she was born\n",birthday);
您将使用 time.h
中的 struct tm
and strftime
的组合:
#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