How to get current time and date in C++?

后端 未结 24 1477
刺人心
刺人心 2020-11-22 06:55

Is there a cross-platform way to get the current date and time in C++?

相关标签:
24条回答
  • 2020-11-22 07:19

    In C++ 11 you can use std::chrono::system_clock::now()

    Example (copied from en.cppreference.com):

    #include <iostream>
    #include <chrono>
    #include <ctime>    
    
    int main()
    {
        auto start = std::chrono::system_clock::now();
        // Some computation here
        auto end = std::chrono::system_clock::now();
    
        std::chrono::duration<double> elapsed_seconds = end-start;
        std::time_t end_time = std::chrono::system_clock::to_time_t(end);
    
        std::cout << "finished computation at " << std::ctime(&end_time)
                  << "elapsed time: " << elapsed_seconds.count() << "s\n";
    }
    

    This should print something like this:

    finished computation at Mon Oct  2 00:59:08 2017
    elapsed time: 1.88232s
    
    0 讨论(0)
  • 2020-11-22 07:19

    You can try the following cross-platform code to get current date/time:

    #include <iostream>
    #include <string>
    #include <stdio.h>
    #include <time.h>
    
    // Get current date/time, format is YYYY-MM-DD.HH:mm:ss
    const std::string currentDateTime() {
        time_t     now = time(0);
        struct tm  tstruct;
        char       buf[80];
        tstruct = *localtime(&now);
        // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
        // for more information about date/time format
        strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
    
        return buf;
    }
    
    int main() {
        std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
        getchar();  // wait for keyboard input
    }
    

    Output:

    currentDateTime()=2012-05-06.21:47:59
    

    Please visit here for more information about date/time format

    0 讨论(0)
  • 2020-11-22 07:19

    Yes and you can do so with formatting rules specified by the currently-imbued locale:

    #include <iostream>
    #include <iterator>
    #include <string>
    
    class timefmt
    {
    public:
        timefmt(std::string fmt)
            : format(fmt) { }
    
        friend std::ostream& operator <<(std::ostream &, timefmt const &);
    
    private:
        std::string format;
    };
    
    std::ostream& operator <<(std::ostream& os, timefmt const& mt)
    {
        std::ostream::sentry s(os);
    
        if (s)
        {
            std::time_t t = std::time(0);
            std::tm const* tm = std::localtime(&t);
            std::ostreambuf_iterator<char> out(os);
    
            std::use_facet<std::time_put<char>>(os.getloc())
                .put(out, os, os.fill(),
                     tm, &mt.format[0], &mt.format[0] + mt.format.size());
        }
    
        os.width(0);
    
        return os;
    }
    
    int main()
    {
        std::cout << timefmt("%c");
    }
    

    Output: Fri Sep 6 20:33:31 2013

    0 讨论(0)
  • 2020-11-22 07:19

    This works with G++ I'm not sure if this helps you. Program output:

    The current time is 11:43:41 am
    The current date is 6-18-2015 June Wednesday 
    Day of month is 17 and the Month of year is 6,
    also the day of year is 167 & our Weekday is 3.
    The current year is 2015.
    

    Code :

    #include <ctime>
    #include <iostream>
    #include <string>
    #include <stdio.h>
    #include <time.h>
    
    using namespace std;
    
    const std::string currentTime() {
    time_t now = time(0);
    struct tm tstruct;
    char buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);
    return buf;
    }
    
    const std::string currentDate() {
    time_t now = time(0);
    struct tm tstruct;
    char buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%B %A ", &tstruct);
    return buf;
    }
    
    int main() {
        cout << "\033[2J\033[1;1H"; 
    std:cout << "The current time is " << currentTime() << std::endl;
        time_t t = time(0);   // get time now
        struct tm * now = localtime( & t );
        cout << "The current date is " << now->tm_mon + 1 << '-' 
             << (now->tm_mday  + 1) << '-'
             <<  (now->tm_year + 1900) 
             << " " << currentDate() << endl; 
    
     cout << "Day of month is " << (now->tm_mday) 
          << " and the Month of year is " << (now->tm_mon)+1 << "," << endl;
        cout << "also the day of year is " << (now->tm_yday) 
             << " & our Weekday is " << (now->tm_wday) << "." << endl;
        cout << "The current year is " << (now->tm_year)+1900 << "." 
             << endl;
     return 0;  
    }
    
    0 讨论(0)
  • 2020-11-22 07:23
    #include <stdio.h>
    #include <time.h>
    
    int main ()
    {
      time_t rawtime;
      struct tm * timeinfo;
    
      time ( &rawtime );
      timeinfo = localtime ( &rawtime );
      printf ( "Current local time and date: %s", asctime (timeinfo) );
    
      return 0;
    } 
    
    0 讨论(0)
  • 2020-11-22 07:26

    I found this link pretty useful for my implementation: C++ Date and Time

    Here's the code I use in my implementation, to get a clear "YYYYMMDD HHMMSS" output format. The param in is for switching between UTC and local time. You can easily modify my code to suite your need.

    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    /**
     * This function gets the current date time
     * @param useLocalTime true if want to use local time, default to false (UTC)
     * @return current datetime in the format of "YYYYMMDD HHMMSS"
     */
    
    string getCurrentDateTime(bool useLocalTime) {
        stringstream currentDateTime;
        // current date/time based on current system
        time_t ttNow = time(0);
        tm * ptmNow;
    
        if (useLocalTime)
            ptmNow = localtime(&ttNow);
        else
            ptmNow = gmtime(&ttNow);
    
        currentDateTime << 1900 + ptmNow->tm_year;
    
        //month
        if (ptmNow->tm_mon < 9)
            //Fill in the leading 0 if less than 10
            currentDateTime << "0" << 1 + ptmNow->tm_mon;
        else
            currentDateTime << (1 + ptmNow->tm_mon);
    
        //day
        if (ptmNow->tm_mday < 10)
            currentDateTime << "0" << ptmNow->tm_mday << " ";
        else
            currentDateTime <<  ptmNow->tm_mday << " ";
    
        //hour
        if (ptmNow->tm_hour < 10)
            currentDateTime << "0" << ptmNow->tm_hour;
        else
            currentDateTime << ptmNow->tm_hour;
    
        //min
        if (ptmNow->tm_min < 10)
            currentDateTime << "0" << ptmNow->tm_min;
        else
            currentDateTime << ptmNow->tm_min;
    
        //sec
        if (ptmNow->tm_sec < 10)
            currentDateTime << "0" << ptmNow->tm_sec;
        else
            currentDateTime << ptmNow->tm_sec;
    
    
        return currentDateTime.str();
    }
    

    Output (UTC, EST):

    20161123 000454
    20161122 190454
    
    0 讨论(0)
提交回复
热议问题