none
C++ MFC如何计算时间差 RRS feed

  • 问题

  • 已知两个时间,知道年月日时分秒的那种格式,如何计算这两个时间相差的秒数,用windows内部函数实现,谢谢!
    2013年9月16日 2:14

答案

  • CTime t1(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
    CTime t2(1999, 3, 20, 22, 15, 0); // 10:15 PM March 20, 1999
    CTimeSpan ts = t2 - t1;             // Subtract 2 CTimes
    ATLASSERT(ts.GetTotalSeconds() == 86400L);
    ATLASSERT((t1 + ts) == t2);       // Add a CTimeSpan to a CTime.
    ATLASSERT((t2 - ts) == t1);       // Subtract a CTimeSpan from a CTime.   
    



    Visual C++ enthusiast, like network programming and driver development. At present is being engaged in the WinCE/Windows Mobile platform embedded development.

    • 已标记为答案 GT_MDRG 2013年9月22日 5:11
    2013年9月18日 3:35
    版主

全部回复

  • 你好,

    按照你的问题,我进行了重现,希望以下代码可以对你有帮助。

    #include <iostream>
    
    #include <ctime>
    
    using namespace std;
    
    
    void main()
    
    {
    
        time_t rawtime;
    
        struct tm * timeinfo;
    
    
        time ( &rawtime );
    
        timeinfo = localtime ( &rawtime );
    
        printf ( "Current local time and date: %s", asctime (timeinfo) );
    
    
        cout << "Press enter" << endl;
    
        cin.ignore();
    
    
        time_t rawtime2;
    
        struct tm * timeinfo2;
    
    
        time ( &rawtime2 );
    
        timeinfo2 = localtime ( &rawtime2 );
    
        printf ( "Later local time and date: %s", asctime (timeinfo2) );
    
           cout << "Press enter" << endl;
    
        cin.ignore();
    
       
    
        printf ( " seconds to press enter. ");
    
           cout << "Elapsed time: " << rawtime2 - rawtime << " seconds" << endl;
    
        cout << endl;
    
           getchar();
    
    }
    


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    2013年9月17日 9:28
  • CTime t1(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
    CTime t2(1999, 3, 20, 22, 15, 0); // 10:15 PM March 20, 1999
    CTimeSpan ts = t2 - t1;             // Subtract 2 CTimes
    ATLASSERT(ts.GetTotalSeconds() == 86400L);
    ATLASSERT((t1 + ts) == t2);       // Add a CTimeSpan to a CTime.
    ATLASSERT((t2 - ts) == t1);       // Subtract a CTimeSpan from a CTime.   
    



    Visual C++ enthusiast, like network programming and driver development. At present is being engaged in the WinCE/Windows Mobile platform embedded development.

    • 已标记为答案 GT_MDRG 2013年9月22日 5:11
    2013年9月18日 3:35
    版主