
Posted by Charles Gutzwiller on December 08, 1999 at 14:46:18:
The MSDN Library discusses many functions that we can use with CTime objects. These functions help us construct CTime objects, extract elements from existing CTime objects and perform conversions.
In my paper entitled “Handling Date Objects” I discuss the construction of CTime objects, as well as provide an example of how to use one of the constructors. Therefore, I would like to focus my attention on extraction and conversion functions. The following are examples of extraction functions that can be used with CTime objects:
GetTime, GetYear, GetMonth, GetDay, GetHour, GetMinute, GetSecond, and GetDayOfWeek.
These are pretty straightforward and it is easy to understand their purpose just by looking at the name of each function. A programmer can use these functions to accomplish many different things. Here is a simple example of what these functions can do:
void main()
{
CTime today = CTime::GetCurrentTime();
int dayOfWeek,day,month,year;
string dayNames[7]= {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday",
"Saturday"};
string monthNames[12]={"January","February","March","April","May","June","July","August","September","October","November","December"};
dayOfWeek = today.GetDayOfWeek();
month = today.GetMonth();
day = today.GetDay();
year = today.GetYear();
cout<<"Today is "< This will output to the console window a message similar to the following: “Today is Wednesday, December 8, 1999” Since GetDayOfWeek will return a 1 for Sunday you must adjust the number by –1 when referring to an element in the dayNames array. This is because array element “Sunday” is in the 0th element of the array. The same is true for the GetMonth function since January is referred to as 1 by the GetMonth function and it is in the 0th element of the monthNames array. void main() This will output to the console window a message similar to the following: “Today is Wednesday, December 08, 1999” This is just a small example of what can be done with CTime functions. There are many other functions that are available which can be used to accomplish any number of tasks.
If you don’t want to go through the hassle of writing all of this code you can use one of the conversion functions available to the CTime class. One such function is Format. The following is equivalent to the code fragment above.
{
CTime today = CTime::GetCurrentTime();
CString s = today.Format("Today is %A, %B %d, %Y" );
printf(s);
}
Post a Follow Up: