Mark As Completed Discussion

Working with Time

When working with time in C++, you have access to a variety of functions and libraries that facilitate efficient time handling. Let's start by understanding the basics.

In the code snippet below, we include the necessary header files iostream and ctime to work with time-related functions:

TEXT/X-C++SRC
1#include <iostream>
2#include <ctime>

To obtain the current date and time based on the system's clock, we use the std::time() function. This function returns a time_t object representing the number of seconds since the UNIX epoch (January 1, 1970).

TEXT/X-C++SRC
1std::time_t now = std::time(0);

Next, we convert the time_t value to a string representing the local date and time using the std::ctime() function:

TEXT/X-C++SRC
1char* dt = std::ctime(&now);

To obtain the UTC (Coordinated Universal Time) date and time, we need to convert the time_t value to the std::tm structure using the std::gmtime() function. This structure represents the date and time broken down into individual components such as year, month, day, hour, minute, and second.

TEXT/X-C++SRC
1std::tm* gmtm = std::gmtime(&now);

We can then convert the std::tm structure back to a string representation using the std::asctime() function:

TEXT/X-C++SRC
1dt = std::asctime(gmtm);

Finally, we output the local date and time as well as the UTC date and time:

TEXT/X-C++SRC
1std::cout << "The local date and time is: " << dt << std::endl;
2std::cout << "The UTC date and time is: " << dt << std::endl;

Try running the code above and observe the output. Notice the difference between the local date and time and the UTC date and time.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment