Structures: combining data elements

This example uses the time_c struct to display the date and time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//Structures: date and time
#include<iostream>
#include<ctime>
using namespace std;
int main() {
   time_t currentTime=time(0); // get time now
   struct tm *now = localtime(&currentTime); //set values for the structure
   cout<<"The year is "<<now->tm_year + 1900<<endl; //
   cout<<"The month is "<<now->tm_mon + 1<<endl;
   cout<<"The day is "<<now->tm_mday<<endl;
   cout<<"The hour is "<<now->tm_hour<<endl;
   cout<<"The minute is "<<now->tm_min<<endl;
   cout<<"The second is "<<now->tm_sec<<endl;
   cout<<"Today is "<<now->tm_mon + 1<<"/"<<now->tm_mday<<"/"<<now->tm_year+1900<<endl;
   cout<<"Today is ";
   switch(now->tm_wday) {
      case 0:cout<<"Sunday\n"; break;
      case 1:cout<<"Monday\n"; break;
      case 2:cout<<"Tuesday\n"; break;
     case 3:cout<<"Wednesday\n"; break;
      case 4:cout<<"Thursday\n"; break;
      case 5:cout<<"Friday\n"; break;
      case 6:cout<<"Saturday\n"; break;
   } //weekday
   if(now->tm_hour<12) cout<<"Good morning\n";
   else if(now->tm_hour<18) cout<<"Good afternoon\n";
   else cout<<"Good evening\n";
   system("pause");
   return 0;
} //main
CODE
Output:
The year is 2017
The month is 12
The day is 12
The hour is 7
The minute is 29
The second is 3
Today is 12/12/2017
Today is Tuesday
Good morning

Challenge: Display the time as 7:29am

NEXT: Finding a Persons age