4

I am writing C++ code for an embedded Linux system. Traditionally, on Linux, the date and time would be retrieved by calling the library function gettimeofday(). But that doesn't feel very object-oriented to me. I would like to instead be able to write code similar to this:

DateTime now = new DateTime;
DateTime duration = new DateTime(2300, DateTime.MILLISECONDS)
DateTime deadline = now + duration;

while(now < deadline){
    DoSomething();
    delete now;
    now = new DateTime()
}

where there is a DateTime class, which can be constructed with the current time or a particular time, and which offers member functions or even overloaded operators to perform operations on the represented date and time.

Is there something like this offered by the C++ standard libraries? I cannot use the Boost libraries on my target system. However, I could consider porting something simple (something implemented with header files only, for example).

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
mikelong
  • 3,694
  • 2
  • 35
  • 40

4 Answers4

6

There is no object-oriented interface for dealing with time and intervals that's part of the standard C++ library.

You might want to look at Boost.Date_Time though. Boost is so useful and well written that its practically a part of the standard C++ library.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
Omnifarious
  • 54,333
  • 19
  • 131
  • 194
3

So porting boost wasn't an option for my target. Instead I had to go with gettimeofday(). There are however some nice macros for dealing with timeval structs in sys/time.h

#include <sys/time.h>

void timeradd(struct timeval *a, struct timeval *b,
          struct timeval *res);

void timersub(struct timeval *a, struct timeval *b,
          struct timeval *res);

void timerclear(struct timeval *tvp);

void timerisset(struct timeval *tvp);

void timercmp(struct timeval *a, struct timeval *b, CMP);

It took a while to find them though because they weren't in the man pages on my machine. See this page: http://linux.die.net/man/3/timercmp

mikelong
  • 3,694
  • 2
  • 35
  • 40
0

I think you should be fine with using stuff from ctime

#include <ctime>

time
difftime
mktime

should do the job in a very portable way. cplusplus.com

Totonga
  • 4,236
  • 2
  • 25
  • 31
0
/usr/include/linux/time.h 

gives structure :-

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

on Linux, may be you could use it...

essbeev
  • 43
  • 1
  • 3