7.2 Date and Time

The CTime class provides a way to represent date and time information easily. The CTimeSpan class represents elapsed time, such as the difference between two CTime objects.

Note:

CTime objects cannot be used to represent dates earlier than January 1, 1980. CTime objects have a resolution of 1 second.

The first procedure in this section shows how to create a CTime object and initialize it with the current time. The next procedure shows how to calculate the difference between two CTime objects and get a CTimeSpan result.

·To get the current time:

1.Allocate a CTime object, as follows:

CTime theTime;

Note:

Uninitialized CTime objects are automatically set to an invalid time.

2.Call the CTime::GetCurrentTime function to get the current time from the operating system. This function returns a CTime object that can be used to set the value of CTime, as follows:

theTime = CTime::GetCurrentTime();

Since GetCurrentTime is a static member function from the CTime class, you must qualify its name with the name of the class and the scope resolution operator (::), CTime::GetCurrentTime().

Of course, the two steps outlined above could be combined into a single program statement as follows:

CTime theTime = CTime::GetCurrentTime();

·To calculate elapsed time:

Use the CTime and CTimeSpan objects to calculate the elapsed time, as follows:

CTime startTime = CTime::GetCurrentTime();

// ... perform time-consuming task ...

CTime endTime = CTime::GetCurrentTime();

CTimeSpan elapsedTime = endTime - startTime;

Once you have calculated elapsedTime, you can use the member functions of CTimeSpan to extract the components of the elapsed-time value.

·To format a string representation of a time or elapsed time:

Use the Format member function from either the CTime or CTimeSpan classes to create a character string representation of the time or elapsed time, as shown by the following example.

CTime t( 1991, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1991

CString s = t.Format( "%A, %B %d, %Y" );

// s == "Tuesday, March 19, 1991"