【问题标题】:Convert date stored as 1912.02.14 to printf as February 2, 1912将存储为 1912.02.14 的日期转换为 printf 为 1912 年 2 月 2 日
【发布时间】:2019-06-01 04:21:10
【问题描述】:

到目前为止,这两个链接一直很有帮助:

但我还不能完全到达那里。使用上面两个链接中的信息,我可以让他们的示例很好地工作:

int main(int argc, char *argv[])
{
   struct tm tm;
   char str_date[256];

   strptime("01/26/12", "%m/%d/%y", &tm);
   strftime(str_date, sizeof(str_date), "%A, %d %B %Y", &tm);
   printf("%s\n", str_date);

   return 0;
}

这会在我的控制台上返回“2012 年 1 月 26 日星期四”,这是正确的。

到目前为止一切顺利。

但是,我在strptime 中使用 yyyy.mm.dd 格式的日期尝试的所有操作都在控制台“?,00?2019”上给了我这个

int main(int argc, char *argv[])
{
   struct tm tm;
   char str_date[256];

   strptime("1912.02.14", "%y.%m.%d", &tm);
   strftime(str_date, sizeof(str_date), "%A, %d %B %Y", &tm);
   printf("%s\n", str_date);

   return 0;
}

如果我能让strptime 正常工作,我可以调整strftime 中的格式说明符以获得我想要的输出。

回答:感谢 BladeMight 的帮助,这段代码非常适合我:

#include <stdio.h>
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);

int main(int argc, char *argv[])
{
   struct tm tm;
   char str_date[256];

   strptime("1912.02.14", "%Y.%m.%d", &tm);
   strftime(str_date, sizeof(str_date), "%B %d, %Y", &tm);
   printf("%s\n", str_date);

   return 0;
 }

如果我遗漏了:

char *strptime(const char *buf, const char *format, struct tm *tm);

然后我得到编译器错误:

78.c: In function ‘main’:
78.c:11:5: warning: implicit declaration of function ‘strptime’; did you  mean ‘strftime’? [-Wimplicit-function-declaration]
 strptime("1912.02.14", "%Y.%m.%d", &tm);
 ^~~~~~~~
 strftime

如果我添加我在顶部发布的第二个链接的答案中提到的两个定义,那么我可以省略 strptime 的定义。

无论我尝试了何种格式,我仍然在我的最终输出中以前导零或前导空格显示 1 位天数的问题。最后,我只是编写了自己的函数来处理这个问题。

感谢大家的帮助,因为我在这个问题上学到了很多东西。

【问题讨论】:

  • 两位数的年份与四位数的年份不同。在第二个例子中使用%Y。
  • 查看 POSIX strptime() — 注意它返回一个值,并检查它返回的内容。

标签: c


【解决方案1】:

您的年份格式不同,因此您应该使用另一种格式,%Y 而不是%y,代码:

#include <stdio.h>
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);
int main(int argc, char *argv[])
{
   struct tm tm;
   char str_date[256];

   strptime("1912.02.14", "%Y.%m.%d", &tm);
   strftime(str_date, sizeof(str_date), "%A, %d %B %Y", &tm);
   printf("%s\n", str_date);

   return 0;
}

输出:

Wednesday, 14 February 1912

【讨论】:

  • char *strptime(const char *buf, const char *format, struct tm *tm); 是多余的,因为它的原型包含在 time.h 中。
  • @BladeMight。谢谢你的帮助!通过对 strftime 中的日期格式进行非常小的调整,它可以准确地输出我正在寻找的内容。
  • @DavidC.Rankin 奇怪,当我尝试在没有此行的情况下进行编译时,gcc 给了我未声明的错误。
  • 你需要#define _XOPEN_SOURCE 700之前你包含头文件。见strptime(3) - Linux manual page注意:评论/* See feature_test_macros(7) */
  • @DavidC.Rankin 谢谢你的信息,不知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多