美文网首页
C++学习笔记3----时间与时间戳

C++学习笔记3----时间与时间戳

作者: ChineseBoy | 来源:发表于2017-06-22 17:08 被阅读1360次

    自 1970 年 1 月 1 日以来经过的秒数:
    time_t time1 = time(0);//这里获取到的其实就是一个long类型的时间戳,是秒级别的,非毫秒级别

        time_t time1 = time(0);
        cout << "time1 = " << time1 << endl;//1498122787
        char * strTime = ctime(&time1);
        cout << "strTime = " << strTime << endl;//Thu Jun 22 17:13:07 2017
    
        time_t startTime = 1498122787;
        double betweenSecond = difftime(time1, startTime);//该函数返回 time1 和 time2 之间相差的秒数。
        cout << "betweenSecond = " << betweenSecond << endl;//Thu Jun 22 17:13:07 2017
    

    1.时间戳转格式化

    time_t t = time(0);
    struct tm *p;
    p=gmtime(&t);
    char s[100];
    strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", p);
    printf("%d: %s\n", (long)t, s); //1498124250: 2017-06-22 09:37:30
    

    2.格式化转时间戳

    long getTick(char *str_time)
    {
        struct tm stm;
        int iY, iM, iD, iH, iMin, iS;
    
        memset(&stm,0,sizeof(stm));
    
        iY = atoi(str_time);
        iM = atoi(str_time+5);
        iD = atoi(str_time+8);
        iH = atoi(str_time+11);
        iMin = atoi(str_time+14);
        iS = atoi(str_time+17);
    
        stm.tm_year=iY-1900;
        stm.tm_mon=iM-1;
        stm.tm_mday=iD;
        stm.tm_hour=iH;
        stm.tm_min=iMin;
        stm.tm_sec=iS;
        return mktime(&stm);
    }
    
    int main()  
    {  
        char str_time[19];  
        printf("请输入时间:"); /*(格式:2011-12-31 11:43:07)*/  
        gets(str_time);  
        printf("%ld\n", GetTick(str_time));  
        return 0;      
    }   
    

    相关文章

      网友评论

          本文标题:C++学习笔记3----时间与时间戳

          本文链接:https://www.haomeiwen.com/subject/vovfcxtx.html