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.