Warszawski Koks
Warszawski Koks

Reputation: 69

C++ boost library local_time_period

Using #include "boost/date_time/posix_time/posix_time.hpp" its possible to get the current local time. I made the function to get the local time:

boost::posix_time::ptime getTime(){
     return boost::posix_time::second_clock::local_time();
}

this function is returning local time of boost::posix_time::ptime type. Example return: Date2017-Nov-05 07:58:36

I want to get some beginning Date and end Date. Then using boost::posix_time::time_period I want to count period of beginning and end dates.

int main(){
boost::posix_time::ptime startDate = getTime();
boost::posix_time::ptime endDate;
string duration; 
cout << "start Date" <<  startDate << endl;

for(int i = 0; i <= 900000000; i++) {
    if(i == 900000000){
        endDate = getTime();
    }
}
cout << "End Date " << endDate << endl;
duration = to_simple_string(boost::posix_time::time_period(startDate,endDate).length());
cout << "Duration:  " << duration << endl;
}

The endDate is in for loop because its the simplest way for me to get it few seconds after startDate.

The cout << "string Duration " << duration << endl; outputs values like for example: Duration: 00:00:04

How to make boost::posix_time::time_period to return only seconds, for example, if my startDate is Date2017-Nov-05 10:00:00 and endDate is Date2017-Nov-05 10:00:10 the function should return just 10, only number.

Upvotes: 0

Views: 298

Answers (1)

harmic
harmic

Reputation: 30587

If you subtract two ptime objects you will get a time_duration object. This object has a total_seconds() method which will give you the total number of seconds.

Eg:

// startTime and endTime are ptime instances
time_duration d = endTime - startTime;
long secs = d.total_seconds();

See: time_duration accessors.

Upvotes: 1

Related Questions