Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The C++ standard library

The C++ standard library

The C++ standard library provides rich functionality, among which is one of the standard libraries for handling time and dates. It provides a set of functions for getting the current time, date, and performing time-related calculations.

The library defines a set of time-related functions and types that allow programmers to handle time in programs. It includes:

Syntax

The following are basic syntax of some commonly used functions in the library:

strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", tm);

Example

Below is an example using library's simple example, showing how to get the current time and format the output.

Example

#include

#include

#include

#include

int

main

(

)

{

   

// Get current time

   

time_t

now

=

time

(

NULL

)

;

   

// Convert current time to local time

   

struct

tm

local_tm

=

localtime

(

&

now

)

;

   

// Use strftime to format time

   

char

buffer

[

80

]

;

   

strftime

(

buffer,

80

,

"%Y-%m-%d %H:%M:%S"

, local_tm

)

;

   

// Output current time

    std

::

cout

<<

"Current local time: "

<<

buffer

<<

std

::

endl

;

   

// Convert current time to UTC

   

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 program above, you will see output similar to the following (the specific 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

Note that due to time zone differences, local time and UTC time may be the same or different.

library is an important tool for handling time and dates in C++. Through the examples above, we can see how to use library to obtain and format the current time. This is very useful when developing applications that need time information, such as logging and scheduled tasks. I hope this article helps beginners better understand and use library.