【发布时间】: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