Get time c++ – Get Current Date & Time in C++ Example using Boost Date Time Library

Get time c++: In this article, we will learn to get Current Date & Time in C++ by the help of  Boost Date Time library.

boost::posix_time::ptime of Boost Date Time Library includes a date and timestamp which provide a particular time point.

Let’s see how to achieve this.

Getting Current Time :

Get current time c++: Using member functions we can get the date, month, year and time in minute and seconds from ptime object.

#include <boost/date_time.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main() {
    // Getting current system time
    boost::posix_time::ptime time_Local =
            boost::posix_time::second_clock::local_time();
    std::cout << "Current System Time : " << time_Local << std::endl;
    // Obtain Date object from ptime object
    boost::gregorian::date date_Obj = time_Local.date();
    std::cout << "Date Object : " << date_Obj << std::endl;
    // Obtain Time object from ptime object
    boost::posix_time::time_duration durObj = time_Local.time_of_day();
    std::cout << "Time Object : " << durObj << std::endl;
    std::cout << "Date's Year : " << time_Local.date().year() << std::endl;
    std::cout << "Date's Month : " << time_Local.date().month() << std::endl;
    std::cout << "Day in the month : " << time_Local.date().day() << std::endl;
    std::cout << "Time in hours : " << time_Local.time_of_day().hours()<< std::endl;
    std::cout << "Time in Minute : " << time_Local.time_of_day().minutes() << std::endl;
    std::cout << "Time in Seconds : " << time_Local.time_of_day().seconds() << std::endl;
}
Output :
Current System Time : 2021-May-30 13:50:51
Date Object : 2021-May-30
Time Object : 13:50:51
Date's Year : 2021
Date's Month : May
Day in the month : 30
Time in hours  : 13
Time in Minute : 50
Time in Seconds :  51

Getting the Current Time in UTC Timezone :

How to get system time in c++: We can also get the time in UTC time zone

#include <boost/date_time.hpp>

#include <iostream>

#include <algorithm>

#include <vector>

#include <string>

int main() {

    // obtaining Current time in UTC zone

    boost::posix_time::ptime timeUTC = boost::posix_time::second_clock::universal_time();

        std::cout << "Current Time in UTC zone is : " << timeUTC << std::endl;

}
Output :
Current Time in UTC zone is : 2021-May-30 14:47:47