简体   繁体   English

如何在C ++中以秒为单位将字符串转换为时间

[英]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++. 我需要在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++ 我对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 ). 您可以使用标准的<time.h>例程( timegmtimelocaltime )。

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 . 请注意, gmtimelocaltime例程不是线程安全的

This fact is due to the pointer-to-static-structure that each one of them returns. 这是由于每个指针都返回的指向静态结构的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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