如何获得当地时间c ++

时间:2017-04-19 10:58:17

标签: c++

我需要获取当前时间(小时,分钟和秒)并添加30分钟。在最后,我需要将结果保存为整数变量。

怎么可能这样做?

我的代码:

int main()
{

  time_t currentTime;
  struct tm *localTime;

  time( &currentTime );
  localTime = localtime( &currentTime );

  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;

}

由于

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作,以便在当地时间提前30分钟获得时间:

    time_t currentTime;
    struct tm *localTime;
    time( &currentTime );
    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( &currentTime );                   // Get the current time
 localTime = localtime( &currentTime );  // 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;
}