簡體   English   中英

如何在C ++中以秒為單位將字符串轉換為時間

[英]How do I convert a string in seconds to time in C++

我有一個字符串,用於存儲自進程啟動以來的秒數。 我需要在C ++中以秒為單位將字符串轉換為時間。 我需要從當前時間中減去該時間,以獲得該過程開始的時間。 我很困惑,我不知道該怎么做。 請有人幫我。 我對C ++有點陌生

如果您使用的是較新的編譯器,則可以嘗試使用Boost時間庫( http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/index.html )或std::chrono (建議)並希望保留在STL中。

這樣的事情可能會起作用:

#include <chrono>
#include <string>

using namespace std::chrono;

std::string elapsed_time_in_s = "123456";
system_clock::time_point then = system_clock::now() - 
    std::chrono::seconds(std::stoll(elapsed_time_in_s));

time_t then_as_time_t = system_clock::to_time_t(then);
#include <sstream>
///
std::stringstream strs(seconds_string);
unsigned int tempTime=0;
if(!(strs >> tempTime))
    //error
//calculate around with tempTime
if(!(strs << tempTime)
    //error
if(!(strs >> seconds_string)
    //error
//new string with the current time

您可以使用標准的<time.h>例程( timegmtimelocaltime )。

例如:

void PrintProcessStartTimeAndDate(int numOfSeconds)
{
    time_t rawtime;
    struct tm* ptm;
    time(&rawtime);
    rawtime -= numOfSeconds;
    ptm = gmtime(&rawtime); // or localtime(&rawtime);
    printf("Process started at %.2d:%.2d:%.2d on %.2d/%.2d/%.2d\n",
            ptm->tm_hour,ptm->tm_min,ptm->tm_sec,ptm->tm_mday,ptm->tm_mon+1,ptm->tm_year+1900);
}

請注意, gmtimelocaltime例程不是線程安全的

這是由於每個指針都返回的指向靜態結構的指針。

暫無
暫無

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

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