C++ date and time

In this article, we will learn about the date and time formats in C++. There is no complete format in C++ for date and time so we inherit it from the c language. To use date and time in c++, <ctime> header file is added in the program.

<ctime>

This header file has four time-related types as follows -

  • Clock_t - It stands for clock type which is an alias of arithmetic type. It represents clock tick counts(units of a time of a constant with system-specific length). Clock_t is the type returned by clock()/.
  • Time_t - It stands for time_type. It represents the time that is returned by function time(). It outputs an integral value as the number of seconds elapsed when time passes by 00:00 hours.
  • Size_t - It is an alias for an unsigned integer type and represents the size of any object in bytes. Size_t is the result of the sizeof() operator which prints sizes and counts.
  • tm - The tm structure holds date and time in the C structure. It is defined as follows -

Date and time functions in c++

Name of the functionPrototype of the functionDescription About the function
mktimetime_t mktime(struct tm *time);This function converts mktime to time_t or calendar date and time.
ctimechar *ctime(const time_t *time);It returns the pointer to a string of the format - day month year hours: minutes: seconds year.
difftimedouble difftime ( time_t time2, time_t time1 );It returns the difference of two-time objects t1 and t2.
gmtimestruct tm *gmtime(const time_t *time);This function returns the pointer of the time in the format of a structure. The time is in UTC.
clockclock_t clock(void);It returns an approximated value for the amount of time the calling program is being run. The value .1 is returned if not available.
localtimestruct tm *localtime(const time_t *time);This function returns the pointer to the tm structure representing local time.
timetime_t time(time_t *time);It represents current time.
strftimesize_t strftime();With the help of this function, we can format date and time in a specific manner.
asctimechar * asctime ( const struct tm * time );The function converts the type object of tm to string and returns the pointer to that string.

Example to print current date and time

Below is the example to print the current date and time in the UTC format.

Code

Output

The local date and time is: Wed Sep 22 16:31:40 2021

The UTC date and time is: Wed Sep 22 16:31:40 2021

The below code tells how to break the tm structure and to print each attribute independently with the use of -> operator.

Code

Output

Number of seconds since January 1,2021 is:: 1632328553
Year:2021
Month: 9
Day: 22
Time: 21:65:53





Latest Courses