简体   繁体   English

C / C ++ time.h,错误时间打印输出,时间比较

[英]C/C++ time.h, wrong time print out, comparison of times

Alright so im experimenting with time.h, what im trying to do is create localtime and compare it to a set time(triggerTime). 好吧,我正在尝试使用time.h,我试图做的是创建本地时间并将其与设置的时间(triggerTime)进行比较。 Simple sounding, but not really, im sure i didnt initialize my time_t trigTime properly, because when i call printf("At the Tone, the time will be: %s", ctime(&trigTime)); 听起来很简单,但不是真的,我不确定我没有正确初始化time_t trigTime,因为当我调用printf(“在Tone时,时间将是:%s”,ctime(&trigTime)); it returns Wen Dec 31 1969 rather then the date i set. 它返回的是Wen 1969年12月31日,而不是我设定的日期。 What is the issue? 有什么问题 Further more what how can i take triggerTime and initialize the struct *tm with it and later compare it to localTimeInfo? 更进一步,我该如何使用triggerTime并使用它初始化结构* tm,然后再将其与localTimeInfo进行比较?

#include <stdio.h>
#include <time.h>

int main() 
{//start main

/****************CURRENT TIME**************************************************/
struct tm *localTimeInfo;//structure to be used to format Local Time
time_t localTime;//create a local time
time(&localTime);//Get the value of local time
localTimeInfo = localtime(&localTime);//store the value of localTime to localTimeInfo

printf("At the Tone, the time will be: %s", asctime(localTimeInfo));
/*****************END CURRENT TIME*********************************************/


/*****************TRIGGER TIME*************************************************/
char *triggerTime = "23 2:30:00 2015";

struct tm *triggerTimeInfo;
time_t trigTime = *triggerTime;

printf("At the Tone, the time will be: %s", ctime(&trigTime));



/*********************END TRIGGER TIME*****************************************/


 return 0;

 }//end main

*triggerTime is '2' - the first character of the string. *triggerTime'2' *triggerTime字符串的第一个字符。 That's indeed a very small value, so it's no surprise you get a date very near to the time_t epoch. 这确实是一个很小的值,因此,您所获得的日期非常接近time_t纪元也就不足为奇了。 C isn't really typesafe, so it won't catch bugs like this. C并不是真正的类型安全,因此它不会捕获此类错误。 See samgak's comment for ideas how to do it properly. 有关如何正确执行操作的想法,请参阅samgak的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM