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

后端 未结 24 1917
刺人心
刺人心 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:35

    New answer for an old question:

    The question does not specify in what timezone. There are two reasonable possibilities:

    1. In UTC.
    2. In the computer's local timezone.

    For 1, you can use this date library and the following program:

    #include "date.h"
    #include 
    
    int
    main()
    {
        using namespace date;
        using namespace std::chrono;
        std::cout << system_clock::now() << '\n';
    }
    

    Which just output for me:

    2015-08-18 22:08:18.944211
    

    The date library essentially just adds a streaming operator for std::chrono::system_clock::time_point. It also adds a lot of other nice functionality, but that is not used in this simple program.

    If you prefer 2 (the local time), there is a timezone library that builds on top of the date library. Both of these libraries are open source and cross platform, assuming the compiler supports C++11 or C++14.

    #include "tz.h"
    #include 
    
    int
    main()
    {
        using namespace date;
        using namespace std::chrono;
        auto local = make_zoned(current_zone(), system_clock::now());
        std::cout << local << '\n';
    }
    

    Which for me just output:

    2015-08-18 18:08:18.944211 EDT
    

    The result type from make_zoned is a date::zoned_time which is a pairing of a date::time_zone and a std::chrono::system_clock::time_point. This pair represents a local time, but can also represent UTC, depending on how you query it.

    With the above output, you can see that my computer is currently in a timezone with a UTC offset of -4h, and an abbreviation of EDT.

    If some other timezone is desired, that can also be accomplished. For example to find the current time in Sydney , Australia just change the construction of the variable local to:

    auto local = make_zoned("Australia/Sydney", system_clock::now());
    

    And the output changes to:

    2015-08-19 08:08:18.944211 AEST
    

    Update for C++20

    This library is now largely adopted for C++20. The namespace date is gone and everything is in namespace std::chrono now. And use zoned_time in place of make_time. Drop the headers "date.h" and "tz.h" and just use .

    As I write this, partial implementations are just beginning to emerge on some platforms.

提交回复
热议问题