The TimeStamp class

Design and implement a class called TimeStamp managing the number of seconds elapsed since 1/1/1970. The class should have three methods: long get(void) to get the number of seconds since 1/1/1970, void set(long t) to set it, void update(void) to read it off the operating system. Furthermore, it must be possible to pass a TimeStamp object (call it timeStamp) on to a stream, as follows: \fbox{\tt cout << timeStamp;} to obtain the date pointed at by timeStamp. Failures should be signalled by throwing an exception called TimeStampException.

You can use the following code to find the number of seconds elapsed since 1970 from the operating system:

#include<sys/time.h>
[...]
struct timeval tv;
struct timezone tz;
int retVal = gettimeofday(&tv, &tz);
long numberOfSecondsSince1970 = tv.tv_sec;

The following code transforms the number of seconds since 1970 into a meaningful date into a string:

#include<string>
#include<ctime>
#include<cstring>
[...]
time_t numberOfSecondsSince1970;
char* buffer = ctime(&numberOfSecondsSince1970);
buffer[strlen(buffer) - 1] = '\0';
std::string theDateString(buffer);

Write the class declaration in a file called timestamp.h and the method implementation in timestamp.cxx. Test your code with the following program tsdriver.cxx:

#include<iostream>
#include "timestamp.h"

int main(int argc, char** argv) {
  using namespace std;
  TimeStamp theTimeStamp;
  theTimeStamp.set(999999999);
  cout << "seconds since 1/1/1970: " << theTimeStamp.get()
       << " corresponding to " << theTimeStamp << endl;
  theTimeStamp.update();
  cout << theTimeStamp << " corresponds to " << theTimeStamp.get() 
       << " number of seconds since 1970" << endl;
  return 0;
}
and verify that the output is:
seconds since 1/1/1970: 999999999 corresponding to Sun Sep  9 03:46:39 2001
Mon Sep 11 11:33:42 2006 corresponds to 1157967222 number of seconds since 1970

The solution to this exercise is included as an example of coding style. The rest of the exercises in this chapter should be solved by the student.



Subsections
Leo Liberti 2008-01-12