zhuwt2008
zhuwt2008
2018-06-25 23:12
采纳率: 95.1%
浏览 1.3k

为什么我的vc++2015时间函数mktime总是返回-1?

代码如下,不论输入什么时间,比如2018-12-30,mktime总是得到-1,很是奇怪,请教高手这是怎么回事?
#include <iostream>
#include <ctime>

int main(int argc, char *argv[])
{
struct tm time0 = { 0 }, time1 = { 0 };
int year, mon, mday;
time0.tm_year = 70; //mktime能接受的最小年数
time0.tm_mon = 0; //1月
time0.tm_mday = 1; //1日
time0.tm_hour = 8; //8时 +8时区在1970年所能接受的最小小时数
time0.tm_hour = 0;
time0.tm_min = 0;
time0.tm_sec = 0;
printf(""); scanf("%4d-%2d-%2d", &year, &mon, &mday);
time1.tm_year = year - 1900; //struct tm里面,tm_year以1900年为基准。
time1.tm_mon = mon - 1;
time1.tm_mday = mday;
time1.tm_hour = 0;
time1.tm_min = 0;
time1.tm_sec = 0;
auto t1 = mktime(&time1);
auto t2 = mktime(&time0);
long seconds = (long)(difftime(t1, t2));
std::cout << seconds << std::endl;
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • caozhy
    已采纳
     #include <iostream>
    #include <ctime>
    
    int main(int argc, char *argv[])
    {
    tm time0, time1;
    int year, mon, mday;
    time0.tm_year = 70; //mktime能接受的最小年数 
    time0.tm_mon = 0; //1月 
    time0.tm_mday = 1; //1日 
    time0.tm_hour = 8; //8时 +8时区在1970年所能接受的最小小时数 
    //time0.tm_hour = 0;
    time0.tm_min = 0;
    time0.tm_sec = 0;
    printf(""); scanf("%4d-%2d-%2d", &year, &mon, &mday);
    time1.tm_year = year - 1900; //struct tm里面,tm_year以1900年为基准。
    time1.tm_mon = mon - 1;
    time1.tm_mday = mday;
    time1.tm_hour = 0;
    time1.tm_min = 0;
    time1.tm_sec = 0;
    auto t1 = mktime(&time1);
    auto t2 = mktime(&time0);
    long seconds = (long)(difftime(t1, t2));
    std::cout << seconds << std::endl;
    }
    
    点赞 评论
  • caozhy

    2018-12-30
    1546099200
    Press any key to continue . . .

    点赞 评论
  • littlesnaka
    littlesnaka 2018-06-26 01:48

    1,注释time0.tm_hour = 0;一句,结果t2=0;
    2,time0.tm_mon = 0改为1,t2=2678400 __int64
    3,我输入的1972-5-29,输出为73238400

    点赞 评论
  • littlesnaka
    littlesnaka 2018-06-26 01:49

    你的tm_hour连续赋值两次,第二次为0,mktime的结果就是-1了

    点赞 评论

相关推荐