将存储为 1912.02.14 的日期转换为 printf 作为 1912 年 2 月 2 日

标签 c

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

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

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 而不是 %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

关于将存储为 1912.02.14 的日期转换为 printf 作为 1912 年 2 月 2 日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058522/

相关文章:

代码忽略 C 中的 IF 命令,FOR 的问题

c++ - 如何通过循环将 OpenMP 线程拆分为子团队

c - C 中的宏和前/后增量

c - 有没有办法操纵我在 C 中移动的位

c - 编译器如何处理 OpenMP 指令

使用POW计算不同数字类型的范围

c - 如何在 C 中找到 unsigned char* 的长度

控制内核中的函数指针

将二进制数转换为十六进制的 C 程序无法转换两个以上的二进制数(如果它们等于十六进制字母)

c - 运行我的 Turbo-C HelloWorld 示例时出错