Working With Time In C++

Working with time with any programming language is always tricky, C++ is no exception.

Getting Current Time

Use the time function to get the current time. Note that time_t has no timezone information, it’s simply UTC offset from epoch (1 January 1970 00:00:00). In most platform it’s stored as 8 bytes integer.

#include 

int main(int argc, char** argv) {
  time_t now;
  time(&now);
  return 0;
}

Formatting / Printing Time

Use C-style strftime function to format time. Note that strftime takes a struct tm * as parameter, so we have to first convert the time_t. Use localtime to convert it into local time zone.


              

struct tm * now_tm = localtime(&now);
char now_str[100];
strftime(now_str, sizeof(now_str), “%F %T %z”, now_tm);
cout << now_str << endl [/cpp] The above pattern string will produce a time format like this: [text] 2015-03-12 12:11:45 +1000 [/text] strftime man page has an excellent explanation of the pattern string. If you want to convert into GMT timezone you can also use gmtime

Parsing Time

This is where things get even more trickier. Not until C++11 standard the language come with a built-in way to parse time strings. Prior to that you have to either write your own parsing function or use 3rd party library like boost.

Check here how to enable C++11 in your toolset.

The new C++11 standard comes with get_time function which can be used to parse string into a struct tm:


              

#include
#include
#include

using namespace std;

int main() {
struct tm tt;
cout << "enter time in YYYY-MM-DD HH:mm format: "; cin >> get_time(&tt, “%Y-%m-%d %H:%M”);
cout << put_time(&tt, “%d %b %Y, %H:%M %z\n”); return 0; } [/cpp] This code will produce output like this: [text] $ ./a.out enter time in YYYY-MM-DD HH:mm format: 2015-06-11 23:44 11 Jun 2015, 23:44 +1000 [/text]

Leave a Reply