Tutorial Study Image

C++ Date and Time


May 29, 2023, Learn eTutorial
680

The C++ standard library does not have a distinct date type. The structs as well as functions for manipulating the date and time are inherited from C. To access date and time-related functions and structures, we must include the ctime header file. The four types that deal with time are clock_t, time_t, size_t, and tm. The system time and date can be represented as an integer via the types clock_t, size_t, and time_t.

There are no appropriate data types available in the C++ standard library. The date and time manipulation structs as well as functions in C are carried over to C++. You must use/include a header file called <ctime> in your C++ application in order to access functions and structures related to dates and times. Clock_t, time_t, size_t, and tm are the four time-related types. The system time and date can be represented as an integer via the types clock_t, size_t, and time_t.

We shall study the C++ date and time formats in this tutorial. Date and time formats are inherited from the c language since C++ lacks a complete implementation of these. The program must include the <ctime> header file in order to use date and time in C++.

<ctime>

The four time-related types in this header file are as follows:

Types Description
Clock_t The term Clock_t refers to the clock type, which is an alias for the arithmetic type. It denotes the number of clock ticks(time units of a constant with system-specific length). The value returned by clock()/ is of type Clock_t.
Time_t Time_t is an abbreviation for time_type. It denotes the time returned by the function time (). When the time reaches 00:00 hours, it produces an integer value that represents the number of seconds that have passed.
Size_t An object's size in bytes is represented by the unsigned integer type known as Size t, which is an alias for that type. Size t is the outcome of the sizeof() operator, which will print sizes as well as counts.
tm - Date and time are stored in the C structure through the tm structure. It is described as follows:

struct tm {  
    int tm_sec; // seconds of the minutes just from 0 to 61
    int tm_min; // minutes of an hour just from 0 to 59  
    int tm_hour; // an hours of the day  just from 0 to 24  
    int tm_mday; // the day of the month just from 1 to 31  
    int tm_mon; //the month of  a year just from 0 to 11  
    int tm_year; // since 1900, year
    int tm_wday; // days have passed since Sunday
    int tm_yday; // days that have passed since January 1st  
    int tm_isdst; // hours of the  daylight savings time  
}  

When using the date and time in the C or C++ programming languages, the tm structure is extremely important. The date and time are stored in this structure as a C structure. Tm structure is frequently used by related functions. Let's look at some C++ date and time examples to fully understand the concept.

Functions For Date And Time

Some of the date and time functions used in C and C++ are listed in the table below.

 

The name of the function Function prototype Description

ctime

 

 

 

char *ctime(const time_t *time);

 

 

a pointer to a string of the format weekday month date hours:minutes: seconds year is returned.

 

 

gmtime

 

 

struct tm *gmtime(const time_t *time);

 

the Coordinated Universal Time (UTC) format, which is effectively Greenwich Mean Time, is returned as a pointer to the tm structure (GMT).

localtime

 

struct tm *localtime(const time_t *time);

 

gives back a pointer to a tm structure that represents local time.

strftime

 

size_t strftime();

 

a format that is used to format the date and time.

asctime

 

 

char * asctime ( const struct tm * time );

 

Returns a pointer to the string after converting a time object of type tm to string.

time

 

 

time_t time(time_t *time);

 

current time is returned.

 

 

Provides a rough estimate of the time the calling program has been executing. If there is no time, a value of.1 is returned.

Clock

 

 

clock_t clock(void);

 

 

 

difftime

 

 

 

double difftime ( time_t time2, time_t time1 );

 

It will just compare the two-time objects, time1, and time2, as well as return the difference.

 

mktime

 

 

 

time_t mktime(struct tm *time);

tm structure is just converted into time_ t format or a calendar equivalent.

 

Date and Time Example in C++

C++ program for showing the local and UTC dates and times


#include <iostream>
#include <ctime>
using namespace std;
 
int main( )
 {
    
time_t ttime = time(0);
    
char* dt = ctime(&ttime);
cout << "The current local date and time is: " << dt << endl;
 
tm *gmt_time = gmtime(&ttime);
dt = asctime(gmt_time);
cout << "The current UTC date and time is:"<< dt << endl;
 }

 

Output:


The current local date and time is: Tue Sep  6 18:37:21 2022

The current UTC date and time is: Tue Sep  6 18:37:21 2022

Explanation of the above program

The time function is used in the example above to retrieve the current time, which is then transformed into a string format and it is displayed in the output. In the same manner, it also gets GMT using the gmtime function as well as converts it to string format using the "asctime" function. Later, it shows the user the GMT time.

program for showing the different members of the "tm" structure.


#include <iostream>
#include <ctime>
using namespace std;
 
int main( )
 {
    
                 time_t ttime = time(0);
                 cout <<"Number of seconds that is elapsed since January 1, 1990:" << ttime << endl;
                 tm *local_time = localtime(&ttime;);
    
                 cout << "Year: "<< 1900 + local_time->tm_year << endl;
                 cout << "Month: "<< 1 + local_time->tm_mon<< endl;
                 cout << "Day: "<< local_time->tm_mday << endl;
                 cout << "Time: "<< 1 + local_time->tm_hour << ":";
                 cout << 1 + local_time->tm_min << ":";
                 cout << 1 + local_time->tm_sec << endl;
 }

 

Output:


Number of seconds that is elapsed since January 1, 1990:1662489811
Year: 2022
Month: 9
Day: 6
Time: 19:44:32

We acquired the local time and then displayed the year, month, day, and time in the format "hour: minutes: seconds," as shown in the result above.

The std::chrono::system clock::now() function can be used in C++ 11 to obtain the current system time as well as the date. Let's look at an example of this. Put this code in the compute time.cpp file. This code determines how long it actually takes for the system to calculate the squares of the first 100 natural numbers.

The program shows how the std::chrono::system clock::now() function can be used in C++ 11 in order to obtain the current system time as well as the date.


#include <iostream>
#include <chrono>
#include <ctime>   
#include <time.h>
#include <string.h>
int main()
{
    int i;
    int sq;
    struct tm tm;
    auto start = std::chrono::system_clock::now();
    for (i=1; i<=100; i++)
      sq = i * i; 
    auto end = std::chrono::system_clock::now();
     std::chrono::duration<double> elapsed_sec
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    localtime_r(&end_time, &tm);
    char CharLocalTimeofUTCTime[30];
    strftime(CharLocalTimeofUTCTime, 30, "%Y-%m-%dT%H:%M:%SZ", &tm);
    //std::string strLocalTimeofUTCTime(CharLocalTimeofUTCTime);
    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

 

Output:


finished computation at Tue Sep  6 19:08:28 2022
elapsed time: 7.1e-08s

In both C++ and C, when working with date and time, the tm structure is extremely important. Tm structure is frequently used by related functions. The previous code snippet utilized time zone conversion to change the time from UTC to IST.

Conclusion

The C++ tutorial on date and time functions has now come to an end. Although bit is a very little topic, it plays a significant role in our understanding of C++.