Current date and time as string

后端 未结 6 1869
梦毁少年i
梦毁少年i 2020-12-04 11:09

I wrote a function to get a current date and time in format: DD-MM-YYYY HH:MM:SS. It works but let\'s say, its pretty ugly. How can I do exactly the sam

6条回答
  •  死守一世寂寞
    2020-12-04 11:47

    Non C++11 solution: With the header, you could use strftime. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.

    #include 
    #include 
    
    int main ()
    {
      time_t rawtime;
      struct tm * timeinfo;
      char buffer[80];
    
      time (&rawtime);
      timeinfo = localtime(&rawtime);
    
      strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
      std::string str(buffer);
    
      std::cout << str;
    
      return 0;
    }
    

提交回复
热议问题