【问题标题】:How do I printf a date in C?如何在 C 中打印日期?
【发布时间】:2014-08-01 10:41:20
【问题描述】:

我正在尝试从诸如“01/01/01”之类的字符串中打印一个日期,并得到诸如“2001 年 1 月 1 日星期一”之类的内容。

我在ctime的人那里找到了一些东西,但真的不知道如何使用它。

有什么帮助吗?

谢谢,

【问题讨论】:

标签: c date ctime


【解决方案1】:

strftime() 完成这项工作。

char buffer[256] = "";
{
  struct tm t = <intialiser here>;
  strftime(buffer, 256, "%H/%M/%S", &t);
}
printf("%s\n", buffer);

【讨论】:

  • strftime 的签名是size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);。您缺少 size_t 参数。
【解决方案2】:

您可能正在寻找strftime

【讨论】:

    【解决方案3】:

    您可以使用strptime 将您的字符串日期转换为struct tm

    struct tm tm;
    strptime("01/26/12", "%m/%d/%y", &tm);
    

    然后用strftime以适当的日期格式打印struct tm

    char str_date[256];
    strftime(str_date, sizeof(str_date), "%A, %d %B %Y", &tm);
    printf("%s\n", str_date);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      相关资源
      最近更新 更多