Converting time_t to int

前端 未结 3 1798
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 03:05

I want to convert a given time into epoch(time_t) and vice versa. can anyone tell what is the routine or algorithm for this?

Thanks

Update

3条回答
  •  醉酒成梦
    2020-12-06 03:49

    To convert a struct tm to a time_t, use mktime. To convert a time_t to a struct tm, use either gmtime or localtime.

    Sample:

    #include 
    #include 
    
    int main () {
        std::time_t now = std::time(0);
    
        std::tm *now_tm = gmtime(&now);
    
        std::tm tomorrow_tm(*now_tm);
    
        tomorrow_tm.tm_mday += 1;
        tomorrow_tm.tm_hour = 0;
        tomorrow_tm.tm_min = 0;
        tomorrow_tm.tm_sec = 0;
    
        std::time_t tomorrow = std::mktime(&tomorrow_tm);
    
        double delta = std::difftime(tomorrow, now);
    
        std::cout << "Tomorrow is " << delta << " seconds from now.\n";
    }
    


    UPDATE 2

    #include 
    #include 
    #include 
    
    // Display the difference between now and 1970-01-01 00:00:00
    // On my computer, this printed the value 1330421747
    int main () {
    
        std::tm epoch_strt;
        epoch_strt.tm_sec = 0;
        epoch_strt.tm_min = 0;
        epoch_strt.tm_hour = 0;
        epoch_strt.tm_mday = 1;
        epoch_strt.tm_mon = 0;
        epoch_strt.tm_year = 70;
        epoch_strt.tm_isdst = -1;
    
        std::time_t basetime = std::mktime(&epoch_strt);
    
        std::time_t curtime = std::time(0);
    
        long long nsecs = std::difftime(curtime, basetime);
    
        std::cout << "Seconds since epoch: " << nsecs << "\n";
        assert(nsecs > 42ll * 365 * 24 * 60 * 60);
    }
    

提交回复
热议问题