c - 我在 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 岁
解决方案
您将使用struct tm
和strftime
from的组合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
推荐阅读
- r - R中的组中位数
- stripe-payments - 如何解决错误 Unsupported Gateway Type for Storage in whmcs using stripe?
- c++ - 使用推力根据索引更改某些元素的值
- lua - NodeMCU lua:adc.readvdd33() 在 ESP8266 上总是返回 65535
- html - 将文本放在切换按钮旁边的更好方法
- java - 在提交表单的同一 jsp 中显示成功消息
- javascript - 处理类构造函数中的 promise 错误
- redirect - 将子域重定向到 Odoo 数据库
- elasticsearch - 无法更改 LXC 上的 vm.max_map_count
- javascript - React useRef 或模块范围以存储与 UI 无关的状态