Linux 下c++程序中打印系统当前时间

    //方案一,将当前时间折算为秒级,再通过相应的时间换算即可
    //此文件必须是c++文件
    /*
    #include
    #include
    using namespace std;
string now() {
 time_t t = time(0);
  char buffer[9] = {0};
   strftime(buffer, 9, "%H:%M:%S", localtime(&t));
    return string(buffer);
    }
    
    
    int main()
    {
    cout<     return 0;
    }
*/


方法二:boost库中的:
#include   // for sprintf()
#include   // for console output
#include   // for std::string
#include

//-----------------------------------------------------------------------------
// Format current time (calculated as an offset in current day) in this form:
//
//  "hh:mm:ss.SSS" (where "SSS" are milliseconds)
//-----------------------------------------------------------------------------
std::string now_str()
{
 // Get current time from the clock, using microseconds resolution
  const boost::posix_time::ptime now =
    boost::posix_time::microsec_clock::local_time();
     // Get the time offset in current day
      const boost::posix_time::time_duration td = now.time_of_day();
       //
        // Extract hours, minutes, seconds and milliseconds.
         //
          // Since there is no direct accessor ".milliseconds()",
           // milliseconds are computed _by difference_ between total milliseconds
            // (for which there is an accessor), and the hours/minutes/seconds
             // values previously fetched.

              //

   const long hours  = td.hours();

   const long minutes  = td.minutes();
    const long seconds  = td.seconds();
    const long milliseconds = td.total_milliseconds() -   ((hours * 3600 + minutes * 60 + seconds) * 1000);
                           //
                            // Format like this:
                             //
                              //  hh:mm:ss.SSS
                               //
                                // e.g. 02:15:40:321
                                 //
                                  //  ^   ^
                                   //  |   |
                                    //  123456789*12
                                     //  ---------10-  --> 12 chars + \0 --> 13 chars should suffice
                                      //
        char buf[40];
        sprintf(buf, "%02ld:%02ld:%02ld.%03ld",
         hours, minutes, seconds, milliseconds);
          return buf;

    }

测试:

   int main()

{

  std::cout << now_str() << '\n';

  }
                                             ///////////////////////////////////////////////////////////////////////////////

你可能感兴趣的:(c++,显示系统时间)