如何在 C++ 中以秒为单位将字符串转换为时间 [英] How do I convert a string in seconds to time in C++

查看:73
本文介绍了如何在 C++ 中以秒为单位将字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,用于存储进程启动后的秒数.我需要将此字符串转换为 C++ 中的秒数.我需要从当前时间中减去这个时间以获得这个过程开始的时间.我很困惑,我不知道该怎么做.请有人帮我.我对 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++

推荐答案

您可以使用标准的 例程(timegmtimelocaltime).

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

例如:

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 例程不是线程安全的.

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.

这篇关于如何在 C++ 中以秒为单位将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆