c++linuxtimegettimeofday

Object-oriented representation of date and time in C++


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).


Solution

  • 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