简体   繁体   中英

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

I have a string that stores the no of seconds since a process started. I need to convert this string with the no of seconds to time in C++. I need to subtract this time from the current time to get the time that this process started. I am confused and I do not know how to go about it. Please could someone help me out. I am a bit new to C++

如果您使用的是较新的编译器,则可以尝试使用Boost时间库( http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/index.html )或std::chrono (建议)并希望保留在STL中。

Something like that could work:

#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

You can use standard <time.h> routines ( time , and gmtime or localtime ).

For example:

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

Please note that gmtime and localtime routines are not thread-safe .

This fact is due to the pointer-to-static-structure that each one of them returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM