Javatpoint Logo
Javatpoint Logo

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.


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 function Prototype of the function Description About the function
mktime time_t mktime(struct tm *time); This function converts mktime to time_t or calendar date and time.
ctime char *ctime(const time_t *time); It returns the pointer to a string of the format - day month year hours: minutes: seconds year.
difftime double difftime ( time_t time2, time_t time1 ); It returns the difference of two-time objects t1 and t2.
gmtime struct 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.
clock clock_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.
localtime struct tm *localtime(const time_t *time); This function returns the pointer to the tm structure representing local time.
time time_t time(time_t *time); It represents current time.
strftime size_t strftime(); With the help of this function, we can format date and time in a specific manner.
asctime char * 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.



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.



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

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA