【问题标题】:C/C++ time.h, wrong time print out, comparison of timesC/C++ time.h,错误时间打印,时间比较
【发布时间】:2015-06-24 02:52:00
【问题描述】:

好吧,我正在尝试使用 time.h,我试图做的是创建本地时间并将其与设定的时间(触发时间)进行比较。听起来很简单,但不是真的,我确定我没有正确初始化我的 time_t trigTime,因为当我调用 printf("At the Tone, the time will be: %s", ctime(&trigTime));它返回 Wen Dec 31 1969 而不是我设置的日期。问题是什么?此外,我怎样才能获取 triggerTime 并用它初始化 struct *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

【问题讨论】:

标签: c++ c time compare


【解决方案1】:

*triggerTime'2' - 字符串的第一个字符。这确实是一个非常小的值,所以你得到一个非常接近 time_t 纪元的日期也就不足为奇了。 C 不是真正的类型安全的,所以它不会捕获这样的错误。有关如何正确执行此操作的想法,请参阅 samgak 的评论。

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 2021-10-18
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多