我需要获取当前时间(小时,分钟和秒)并添加30分钟。在最后,我需要将结果保存为整数变量。
怎么可能这样做?
我的代码:
int main()
{
time_t currentTime;
struct tm *localTime;
time( ¤tTime );
localTime = localtime( ¤tTime );
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
std::cout << "Execute at: " << Hour << ":" << Min << ":" << Sec << std::endl;
return 0;
}
由于
答案 0 :(得分:1)
您可以执行以下操作,以便在当地时间提前30分钟获得时间:
time_t currentTime;
struct tm *localTime;
time( ¤tTime );
currentTime += 1*30*60;
localTime= localtime(&utc);
localTime结构现在比当前时间早30分钟。您可以像以前一样以整数形式获取值。
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
如果你需要字符串,你可以
std::string strAheadTime = asctime(localTime);
答案 1 :(得分:0)
你可以像这样实现 -
#include <iostream>
#include <ctime>
int main()
{
time_t currentTime;
struct tm *localTime;
time( ¤tTime ); // Get the current time
localTime = localtime( ¤tTime ); // Convert the current time to the local time
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
std::cout << "The current time is : " << Hour << ":" << Min << ":" << Sec << std::endl;
//increase local time by 30 minutes and adjust minutes and hour.
int IncMin = Min + 30;
if(IncMin >= 60){
int res = IncMin/60;
int newMin = IncMin % 60;
Hour += res;
if(Hour > 23){
Hour = 00;
}
std::cout << "The updated time is : " << Hour << ":" << newMin << ":" << Sec << std::endl;
}
return 0;
}