Converting time_t to int

前端 未结 3 1795
没有蜡笔的小新
没有蜡笔的小新 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

    Whatever you're doing with time_t, you'll probably be best off using the library. Then you can convert to and from time_t, if necessary. Hopefully you can just do what you need in

    #include 
    
    int main() {
        auto a = std::chrono::system_clock::now()
        time_t b = std::chrono::system_clock::to_time_t(a);
        auto c = std::chrono::system_clock::from_time_t(b);
    }
    

    Update:

    The C++ standard library doesn't yet have an API for dates as good as is for time. You can use the Boost date library or you can fall back on the C date library:

    #include 
    #include 
    #include 
    
    int main() {
        std::tm epoch_start = {};
        epoch_start.tm_sec = 0;
        epoch_start.tm_min = 0;
        epoch_start.tm_hour = 0;
        epoch_start.tm_mday = 1;
        epoch_start.tm_mon = 0;
        epoch_start.tm_year = 70;
        epoch_start.tm_wday = 4;
        epoch_start.tm_yday = 0;
        epoch_start.tm_isdst = -1;
    
        std::time_t base = std::mktime(&epoch_start);
    
        auto diff = std::chrono::system_clock::now() - std::chrono::system_clock::from_time_t(base);
        std::chrono::seconds s = std::chrono::duration_cast(diff);
    
        std::cout << s.count() << '\n';
    }
    

提交回复
热议问题