到目前为止,这两个链接很有帮助:
但我还不能完全到达那里。使用上面两个链接中的信息,我可以让他们的示例正常工作:
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/