Case Study: Displaying the Current Time in C++

You can invoke the time(0) function to return the current time.

The problem is to develop a program that displays the current time in GMT (Greenwich Mean Time) in the format hour:minute:second, such as 13:19:8.

The time(0) function, in the ctime header file, returns the current time in seconds elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1. This time is known as the UNIX epoch. The epoch is the point when time starts. 1970 was the year when the UNIX operating system was formally introduced.

Figure 2.1 Invoking time(0) returns the number of seconds since the Unix epoch

You can use this function to obtain the current time, and then compute the current second, minute, and hour as follows:

  1. Obtain the total seconds since midnight, January 1, 1970, in totalSeconds by invok­ing time(0) (e.g., 1203183086 seconds).
  2. Compute the current second from totalSeconds % 60 (e.g., 1203183086 seconds % 60 = 26, which is the current second).
  3. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 (e.g., 1203183086 seconds / 60 = 20053051 minutes).
  4. Compute the current minute from totalMinutes % 60 (e.g., 20053051 minutes % 60 = 31, which is the current minute).
  5. Obtain the total hours totalHours by dividing totalMinutes by 60 (e.g., 20053051 minutes / 60 = 334217 hours).
  6. Compute the current hour from totalHours % 24 (e.g., 334217 hours % 24 = 17, which is the current hour).

Listing 2.9 shows the complete program followed by a sample run.

Listing 2.9 ShowCurrentTime.cpp

1 #include <iostream>

2 #include <ctime>

3 using namespace std;

4

5 int main()

6 {

7    // Obtain the total seconds since the midnight, Jan 1, 1970

8    int totalSeconds = time(0);

9

10    // Compute the current second in the minute in the hour

11    int currentSecond = totalSeconds % 60;

12

13    // Obtain the total minutes

14    int totalMinutes = totalSeconds / 60;

15

16    // Compute the current minute in the hour

17    int currentMinute = totalMinutes % 60;

18

19    // Obtain the total hours

20    int totalHours = totalMinutes / 60;

21

22    // Compute the current hour

23    int currentHour = totalHours % 24;

24

25    // Display results

26    cout << “Current time is ” << currentHour << “:”

27    << currentMinute << “:” << currentSecond << ” GMT” << endl;

28

29    return 0;

30 }

When time(0) (line 8) is invoked, it returns the difference, measured in seconds, between the current GMT and midnight, January 1, 1970 GMT.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *