Manipulating Dates and Times
In C++, manipulating dates and times is made easier with the help of C++ libraries. These libraries provide functionality to perform various operations on date and time objects.
Let's start by learning how to obtain the current date and time based on the system's clock. We can use the std::time()
function to get the current time as a time_t
object representing the number of seconds since the UNIX epoch (January 1, 1970):
1std::time_t now = std::time(0);
To convert the time_t
value to a string representing the local date and time, we can use the std::ctime()
function:
1char* dt = std::ctime(&now);
Similarly, we can obtain the UTC (Coordinated Universal Time) date and time by converting the time_t
value to the std::tm
structure using the std::gmtime()
function:
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 can output the local date and time as well as the UTC date and time using std::cout
:
1std::cout << "Local date and time: " << dt;
2std::cout << "UTC date and time: " << dt;
Try running the code above to see the output. You will observe the difference between the local date and time and the UTC date and time.
xxxxxxxxxx
int main() {
// Get the current date and time
std::time_t now = std::time(0);
// Convert the time_t object to a string representing the local date and time
char* dt = std::ctime(&now);
std::cout << "Local date and time: " << dt;
// Convert the time_t object to the tm structure representing UTC date and time
std::tm* gmtm = std::gmtime(&now);
// Convert the tm structure back to a string representation
dt = std::asctime(gmtm);
std::cout << "UTC date and time: " << dt;
return 0;
}