簡體   English   中英

將 time_t 轉換為 int

[英]Converting time_t to int

我想將給定的時間轉換為紀元(time_t),反之亦然。 誰能說出這的例程或算法是什么?

謝謝

更新

 epoch_strt.tm_sec = 0;
 epoch_strt.tm_min = 0;
 epoch_strt.tm_hour = 0;
epoch_strt.tm_mday = 1;
epoch_strt.tm_mon = 1;
epoch_strt.tm_year = 70;
 epoch_strt.tm_isdst = -1;

double nsecs = difftime(curtime, basetime);//current time from system, I converrting it to struct tm

但這總是出於某種原因返回 32399 。

您應該將其轉換為long int而不是int

long int t = static_cast<long int> (time(NULL));

int可能不足以容納時間,例如,在我的平台上, time_t__int64typedef

無論您使用time_t做什么,最好使用<chrono>庫。 然后,您可以根據需要在time_t進行轉換。 希望你可以在<chrono>做你需要的

#include <chrono>

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);
}

更新:

C++ 標准庫還沒有像<chrono>適用於時間的 API。 您可以使用 Boost 日期庫,也可以使用 C 日期庫:

#include <ctime>
#include <chrono>
#include <iostream>

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<std::chrono::seconds>(diff);

    std::cout << s.count() << '\n';
}

要將struct tm轉換為time_t ,請使用mktime 要將time_t轉換為struct tm ,請使用gmtimelocaltime

樣品

#include <iostream>
#include <ctime>

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";
}


更新 2

 #include <iostream> #include <ctime> #include <cassert> // 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); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM