Rafał’s random comments – programming, IT, other

April 13, 2008

Using date time in C++ with Boost.

Filed under: c++ — limcore @ 11:33 pm
Tags:

Using time/date in C++ with Boost.

Task of getting time, date and operating on this data is not trivial. If you take into account leap years, date calculations, time zones, microseconds on various platforms etc.

Therefore, boost date_time lib is the standard solution.

Since I was asked online (Monobi) how to use it, I thought I may as well write it in the blog so that other can use it as well.

Boost Date Time have nice documentation. And here you can read 2 minute intro.

Boost is a collection of libraries. It is most easy to install on Linux, i.e. on Ubuntu.

apt-get install libboost-date-time-dev

Now the needed .h + .a files (headers and compiled library objects) are installed.

Create a program main.cpp with content:

#include
#include “boost/date_time/gregorian/gregorian.hpp”
#include “boost/date_time/posix_time/posix_time.hpp”

int main() {
using namespace boost::posix_time; /* put that in functions where you work with time (namespace) */

ptime now = microsec_clock::local_time(); // current *LOCAL TIMEZONE* time/date

std::cout << now.time_of_day().hours() << std::endl; // time_od_day gets the time of day in time "now" // hours extract as integer the hours part time_duration tod = now.time_of_day(); std::cout << tod.hours() << ':' << tod.minutes() << ':' << tod.seconds() << std::endl; std::cout << tod << std::endl; // also works } [/sourcecode] To compile it (under in example Linux) do: g++ main.cpp -ggdb3 -o main.elf -lboost_date_time assuming that lib boost date time dev is installed (see above).

1 Comment »

  1. Thanks found it a useful intro!

    Comment by Ash McConnell — June 9, 2009 @ 12:13 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Create a free website or blog at WordPress.com.