【问题标题】:What format specifier do I use in C for dates?我在 C 中为日期使用什么格式说明符?
【发布时间】:2021-11-16 19:55:46
【问题描述】:

这是我的代码(我知道使用 %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 岁

【问题讨论】:

  • int birthday = 22/07/2003; 你觉得这有什么作用?
  • 22/07/2003(22/07)/2003 相同。 22/07 的计算结果为 3,而 3/2003 为零。所以你已经将birthday 初始化为0。问题不在于格式说明符。
  • 令人着迷。 22/07/20030,但 2003-07-221974 :D
  • 一般情况下,可以考虑使用strftime()来格式化时间和日期,它有自己的一组格式说明符。
  • @YakovGalka,现在试试2003-08-22。我怀疑“Ruby Octal”的结果不是 1973 年。 ;-)

标签: c date format-specifiers


【解决方案1】:

您将使用来自time.hstruct tmstrftime 的组合:

#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

【讨论】:

  • 注意:因为May 2017,看起来现在每个人都在 1900 年/之后出生,所以对于我们这些人来说,.tm_year &gt;= 0
【解决方案2】:

C 中没有内置“日期”类型。您可以将字符串用于任意文本;类似:

const char *birthday = "22/07/2003";

您可以使用 printf 格式的%s 打印

printf("on %s she was born\n",birthday);

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多