none
mktime fails for dates before 1970 RRS feed

  • Frage

  • I ran the following code in VS Express 2013 for Windows Desktop

    #pragma warning(disable: 4996)
    
    #include <ctime>
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        static char        datec[] = "mm/dd/yy hh/mm/ss PM";
        const static char  datef[] = "%m/%d/%y %I:%M:%S %p";
        static struct tm   dates = {0};
        static time_t      datet;
        dates.tm_mon = 1 - 1; 
        dates.tm_mday = 1;
        dates.tm_year = 2018 - 1900;
        datet = mktime(&dates);
        dates = *localtime(&datet);
        strftime(datec, sizeof datec, datef, &dates);
        cout << "Test 1: time_t = " << datet << ", char = '" << datec << "'\n";
        dates.tm_year = 1960-1900;
        datet = mktime(&dates);
        cout << "Test 2: time_t = " << datet <<"  <=== !?!?!?\n";
        system("pause");
        return 0;
    }
    

    and got the following output

    Test 1: time_t = 1514793600, char = '01/01/18 12:00:00 AM'
    Test 2: time_t = -1  <=== !?!?!?
    Press any key to continue . . .

    Can anyone explain why test 2 failed?  1960 was not that long ago.

    Samstag, 11. August 2018 00:34

Antworten

  • On 8/10/2018 8:34 PM, Barry-Schwarz wrote:

    Can anyone explain why test 2 failed?  1960 was not that long ago.

    time_t represents time as the number of seconds since Unix epoch - midnight 1/1/1970. Largely for historical reasons. It's thus incapable of representing any time prior to that.

    • Als Antwort markiert Barry-Schwarz Samstag, 11. August 2018 08:06
    Samstag, 11. August 2018 00:44
  • time_t is documented as representing time values as The number of seconds since January 1, 1970, 0:00 UTC, and the mktime documentation says it returns -1  "If timeptr references a date before midnight, January 1, 1970, or if the calendar time cannot be represented,"
    • Als Antwort markiert Barry-Schwarz Samstag, 11. August 2018 08:06
    Samstag, 11. August 2018 00:54

Alle Antworten

  • On 8/10/2018 8:34 PM, Barry-Schwarz wrote:

    Can anyone explain why test 2 failed?  1960 was not that long ago.

    time_t represents time as the number of seconds since Unix epoch - midnight 1/1/1970. Largely for historical reasons. It's thus incapable of representing any time prior to that.

    • Als Antwort markiert Barry-Schwarz Samstag, 11. August 2018 08:06
    Samstag, 11. August 2018 00:44
  • time_t is documented as representing time values as The number of seconds since January 1, 1970, 0:00 UTC, and the mktime documentation says it returns -1  "If timeptr references a date before midnight, January 1, 1970, or if the calendar time cannot be represented,"
    • Als Antwort markiert Barry-Schwarz Samstag, 11. August 2018 08:06
    Samstag, 11. August 2018 00:54