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:
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).
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:
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.
1std::tm* gmtm = std::gmtime(&now);
We can then convert the std::tm
structure back to a string representation using the std::asctime()
function:
1dt = std::asctime(gmtm);
Finally, we output the local date and time as well as the UTC date and time:
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.
xxxxxxxxxx
int main() {
// current date/time based on current system
std::time_t now = std::time(0);
// convert now to string form
char* dt = std::ctime(&now);
std::cout << "The local date and time is: " << dt << std::endl;
// convert now to tm struct for UTC
std::tm* gmtm = std::gmtime(&now);
dt = std::asctime(gmtm);
std::cout << "The UTC date and time is: " << dt << std::endl;
return 0;
}