Mark As Completed Discussion

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):

TEXT/X-C++SRC
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:

TEXT/X-C++SRC
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:

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 can output the local date and time as well as the UTC date and time using std::cout:

TEXT/X-C++SRC
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.

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