5.1. Obtaining the Current Date and Time
Problem
You want to retrieve the current date and time from the user’s computer, either as a local time or as a Coordinated Universal Time (UTC).
Solution
Call the time function from the <ctime> header, passing a value of 0 as the parameter. The result will be a time_t value. You can use the gmtime function to convert the time_t
value to a tm structure representing the current UTC
time (a.k.a. Greenwich Mean Time or GMT); or, you can use the localtime function to convert the time_t
value to a tm structure representing the local time.
The program in Example 5-1 obtains the
current date/time, and then converts it to local time and outputs it. Next, the program
converts the current date/time to a UTC date/time and outputs that.
Example 5-1. Getting the local and UTC times
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
// Current date/time based on current system
time_t now = time(0);
// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;
// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}
}Discussion
The time function returns a time_t type, which is an implementation-defined arithmetic type for representing a time period (a.k.a. a time ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access