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

2018-12-31 15:59发布

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

22条回答
几人难应
2楼-- · 2018-12-31 16:57

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

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 17:00

You can also directly use ctime():

#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  printf ( "Current local time and date: %s", ctime (&rawtime) );

  return 0;
} 
查看更多
像晚风撩人
4楼-- · 2018-12-31 17:03

You can use the following code to get the current system date and time in C++ :

#include <iostream>
#include <time.h> //It may be #include <ctime> or any other header file depending upon
                 // compiler or IDE you're using 
using namespace std;

int main() {
   // current date/time based on current system
   time_t now = time(0);

   // convert now to string form
   string dt = ctime(&now);

   cout << "The local date and time is: " << dt << endl;
return 0;
}

PS: Visit this site for more information.

查看更多
皆成旧梦
5楼-- · 2018-12-31 17:04
auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.

Get the current time either using std::time() or std::chrono::system_clock::now() (or another clock type).

std::put_time() (C++11) and strftime() (C) offer a lot of formatters to output those times.

#include <iomanip>
#include <iostream>

int main() {
    auto time = std::time(nullptr);
    std::cout
        // ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
        << std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
        // %m/%d/%y, e.g. 07/31/17
        << std::put_time(std::gmtime(&time), "%D"); 
}

The sequence of the formatters matters:

std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Monday

The formatters of strftime() are similar:

char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
    std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}

Often, the capital formatter means "full version" and lowercase means abbreviation (e.g. Y: 2017, y: 17).


Locale settings alter the output:

#include <iomanip>
#include <iostream>
int main() {
    auto time = std::time(nullptr);
    std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("en_US.utf8"));
    std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("en_GB.utf8"));
    std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("de_DE.utf8"));
    std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("ja_JP.utf8"));
    std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
    std::cout.imbue(std::locale("ru_RU.utf8"));
    std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");        
}

Possible output (Coliru, Compiler Explorer):

undef: Tue Aug  1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017年08月01日 08時29分30秒
ru_RU: Вт 01 авг 2017 08:29:30

I've used std::gmtime() for conversion to UTC. std::localtime() is provided to convert to local time.

Heed that asctime()/ctime() which were mentioned in other answers are marked as deprecated now and strftime() should be preferred.

查看更多
登录 后发表回答