C++ Standard Library<ctime>
The C++ standard library provides rich functionality, among which<ctime>is one of the standard libraries for handling time and dates. It provides a set of functions for obtaining the current time, date, and performing time-related calculations.
<ctime>The library defines a set of time-related functions and types that allow programmers to handle time in programs. It includes:
time_t: represents a time type, usually a long integer.tm: a struct used to represent the various parts of time, such as year, month, day, hour, etc.- A series of functions, such as
time(),localtime(),gmtime(),strftime()etc.
Syntax
The following are<ctime>Basic syntax of some commonly used functions in the library:
-
Get the current time (in seconds, calculated from January 1, 1970):
time_t t = time(NULL);
-
will
time_tConvert time of type totmStructure:struct tm *tm = localtime(&t);
-
will
time_tConvert the time of type to Coordinated Universal Time (UTC)tmStructure:struct tm *tm_utc = gmtime(&t);
-
Formatting time:
char buffer[80]; strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", tm);
Example
Below is an example using<ctime>A simple example of the library, showing how to get the current time and format the output.
Example
#include <ctime>
#include <iomanip>
#include <sstream>
int main() {
// get the current time
time_t now = time(NULL);
// convert the current time to local time
struct tm *local_tm = localtime(&now);
// use strftime to format the time
char buffer[80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", local_tm);
// output the current time
std::cout << "Current local time: " << buffer << std::endl;
// convert the current time to UTC time
struct tm *utc_tm = gmtime(&now);
// format UTC time
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", utc_tm);
// output UTC time
std::cout << "Current UTC time: " << buffer << std::endl;
return 0;
}
Running the above program, you will see output similar to the following (the exact time depends on when you run the program):
Current local time: 2023-04-01 12:34:56 Current UTC time: 2023-04-01 12:34:56
Please note that due to time zone differences, local time and UTC time may be the same or may differ.
<ctime>The library is an important tool for handling time and date in C++. Through the above examples, we can see how to use<ctime>library to obtain and format the current time. This is very useful when developing applications that require time information, such as logging, scheduled tasks, etc. I hope this article can help beginners better understand and use<ctime>Library.