Getting current time of a different timezone using C++

后端 未结 4 1151
刺人心
刺人心 2021-01-05 05:17

How do i get the current time of a different time zone? Example, i need to know the current time in Singapore where as my system is set to PT time.

4条回答
  •  长情又很酷
    2021-01-05 06:15

    New answer for a very old question.

    Given a C++11 or C++14 compiler, and this timezone library, the current time in Singapore is:

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

    which just output for me:

    2015-08-19 05:25:05.453824 SGT
    

    This gives the current local date, time and abbreviation in use. And it is based off of the library and the IANA timezone database.

    std::chrono::system_clock::now() returns a time stamp in the UTC timezone. This program locates the timezone information for "Asia/Singapore", and translates the UTC timestamp into a pair representing the local time and the current timezone for that location.

    The above program is independent of the computer's current timezone.

    C++20 Update

    In C++20 you can now do this (once your vendor ships it):

    #include 
    #include 
    
    int
    main()
    {
        using namespace std::chrono;
        std::cout << zoned_time{"Asia/Singapore", system_clock::now()} << '\n';
    }
    

    Output:

    2015-08-19 05:25:05.453824 SGT
    

提交回复
热议问题