所以我需要专门使用struct tm来打印我的生日,这是我成功的。但是,我还需要使用strftime()以不同的格式打印它。 这就是我遇到问题的地方,因为strftime()只识别指针参数。
#include <stdio.h>
#include <time.h>
int main(){
struct tm str_bday;
time_t time_bday;
char buffer[15];
str_bday.tm_year = 1994 - 1900 ;
str_bday.tm_mon = 7 - 1;
str_bday.tm_mday = 30;
str_bday.tm_hour = 12;
str_bday.tm_min = 53;
time_bday = mktime(&str_bday);
if(time_bday == (time_t)-1)
fprintf(stdout,"error\n");
else
{
fprintf(stdout,"My birthday in second is: %ld \n",time_bday);
fprintf(stdout,"My birthday is: %s\n", ctime(&time_bday));//Wed July 22 12:53:00 1998
strftime(buffer,15,"%d/%m/%Y",time_bday);
fprintf(stdout,"My birthday in D/M/Y format is %s",buffer);
}
return 0;
}
错误是:
Error: passing argument 4 of ‘strftime’ makes pointer from integer without a cast
expected ‘const struct tm * restrict’ but argument is of type ‘time_t’
有人可以告诉我如何解决它吗?
编辑:将time_bday更改为&amp; str_bday有效!但现在程序每次运行都会输出随机时间和日期。
编辑:在strftime()之后使用put(缓冲区)而不是fprintf(),它完美地运行了。另外,将缓冲区[15]更改为缓冲区[30],因为我有小时,分钟和秒。答案 0 :(得分:5)
通过查看strftime
的原型,您可以看到您应该传递const struct tm*
作为最后一个参数:
size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr);
在您的情况下,&str_bday
代替time_bday
。
struct tm
有两个你没有初始化的字段,因此会获取不确定的值,导致你看到的时间跳跃。在插入值之前,您可以使用struct tm str_bday = {0}
将所有字段初始化为零。
答案 1 :(得分:0)
mktime(&str_bday);
在struct tm
的计算中取决于time_t
的各种成员 1 。
首先将成员初始化为0
是一种很好的做法。
// struct tm str_bday;
struct tm str_bday = { 0 };
OP的代码无法初始化某些成员,例如tm_sec
,这肯定会导致错误的结果。
然而,初始化所有相关成员也很重要。 OP的代码不会分配tm_isdst
和struct tm str_bday = { 0 }
,这就像
str_bday.tm_isdst = 0; // Set time stamp to **standard** time.
问题在于OP's school,该日期的日光时间设置肯定是夏令时。
// add
str_bday.tm_isdst = -1; // Let mktime() determine DST setting
// or if one knowns it is daylight time.
str_bday.tm_isdst = 1; // Set time stamp to **daylight** time.
// or if one knowns it is standard time.
str_bday.tm_isdst = 0; // Set time stamp to **standard** time.
在ctime(&time_bday)
// My birthday is: Sat Jul 30 13:53:00 1994
My birthday is: Sat Jul 30 12:53:00 1994
更正后的代码
#include <locale.h>
#include <time.h>
int main() {
struct tm str_bday = { 0 };
time_t time_bday;
char buffer[15];
str_bday.tm_year = 1994 - 1900;
str_bday.tm_mon = 7 - 1;
str_bday.tm_mday = 30;
str_bday.tm_hour = 12;
str_bday.tm_min = 53;
str_bday.tm_isdst = -1;
time_bday = mktime(&str_bday);
strftime(buffer, sizeof buffer, "%d/%m/%Y", &str_bday);
if (time_bday == (time_t) -1) {
fprintf(stdout, "error\n");
} else {
// Do not assume `long`. Better to cast to a wide type.
fprintf(stdout, "My birthday in second is: %lld \n", (long long) time_bday);
fprintf(stdout, "My birthday is: %s", ctime(&time_bday));
// strftime(buffer,15,"%d/%m/%Y",time_bday);
strftime(buffer, sizeof buffer, "%d/%m/%Y", &str_bday);
fprintf(stdout, "My birthday in D/M/Y format is %s\n", buffer);
}
return 0;
}
1 成员tm_wday
和tm_yday
不参与计算,但会更新。