Simplest way to get current time in current timezone using boost::date_time?

前端 未结 3 1107
误落风尘
误落风尘 2021-01-04 09:41

If I do date +%H-%M-%S on the commandline (Debian/Lenny), I get a user-friendly (not UTC, not DST-less, the time a normal person has on their wristwatch) time p

3条回答
  •  时光取名叫无心
    2021-01-04 10:22

    I haven't found other answers to be convenient enough, so here is an example that showcases how to get a local or universal time with full control of units:

    #include 
    #include 
    
    #include 
    
    int main()
    {
        auto const now = boost::posix_time::microsec_clock::local_time(); // or universal_time() for GMT+0
        if (now.is_special()) {
            // some error happened
            return 1;
        }
    
        // example timestamp (eg for logging)
        auto const t = now.time_of_day();
        boost::format formater("[%02d:%02d:%02d.%06d]");
        formater % t.hours() % t.minutes() % t.seconds() % (t.total_microseconds() % 1000000);
        std::cout << formater.str();
    }
    

    Note: the time_of_day struct has no .microseconds() or .nanoseconds() functions, there is only .fractional_seconds() which returns an integer that is a multiple of configuration-dependent unit. .num_fractional_digits() can be used to obtain precision information where 10 ^ frac_digits is the number of fractional_seconds that is equal to 1 second.

    To obtain configuration-independent sub-second units one can perform modulo with the total_ milli/micro/nano _seconds() functions as a workaround.

提交回复
热议问题