C++ Date and Time Functions with Examples

In this tutorial, we will discuss the date and time manipulation in C++.

We will learn about the date and time formats in C++ as we go over them.

Since C++ doesn’t have a full format for date and time, we take it from the C language.

To use date and time in a C++ program, the <ctime> header file must be added.

Std::ctime

The ctime() function in C++ changes the given time since the beginning of time to a local calendar time and then to a string of characters.

It is defined in the <ctime> header file. This header was originally in the C standard library as "time.h". Further, this header is part of the C-style date and time library.

The ctime() function takes as a parameter a pointer to a time_t object and returns a string that looks like this:

Www Mmm dd hh:mm:ss yyyy
  • Www – the day of the week (MonTueWedThuFriSatSun).
  • Mmm – the month (JanFebMarAprMayJunJulAugSepOctNovDec).
  • dd – the day of the month
  • hh – hours
  • mm – minutes
  • ss – seconds
  • yyyy – years

Types of ctime

The header <ctime> has four types that deal with time. They are tm, clock_t, time_t, and size_t.

Each type, clock_t, size_t, and time_t, use an integer to represent the system time and date.

In the form of a C structure, the date and time are stored in the tm structure.

  • Clock_t It stands for arithmetic type, also known as clock type. It shows how many times a clock ticks (units of a time of a constant with system-specific length). Clock_t is the type that clock()/ gives back.

  • Time_t It represents time_type. It indicates the time returned by the function time(). It returns an integral value as the number of seconds elapsed when 00:00 hours have passed.

  • Size_t It is an alias for the unsigned integer data type and represents the size in bytes of any object. Size_t represents the output of the sizeof() operator, which displays sizes and counts.

  • tm tm structure stores date and time information of C structure.

The “tm” Structure

The tm structure holds the date and time of the C structure. Here’s how to define the “tm” structure:

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

Date & Time Functions In C++ With Examples

The table below shows some of the date and time functions we use in C and C++.

Function NameFunction PrototypeDescription
ctimechar *ctime(const time_t *time);Returns a pointer to a string with the format weekday month date hours:minutes:seconds year.
gmtimestruct tm *gmtime(const time_t *time);Returns a pointer to the tm structure in the Coordinated Universal Time (UTC) format, which is basically Greenwich Mean Time (GMT).
localtimestruct tm *localtime(const time_t *time);Returns pointer to tm structure representing local time.
strftimesize_t strftime();Used to format date and time in a specific format.
asctimechar * asctime ( const struct tm * time );It converts a time object of type tm to a string and returns a pointer to this string.
timetime_t time(time_t *time);Returns current time.
clockclock_t clock(void);Returns an estimate of how long the program that is called it has been running. If the time is not available, a value of.1 is given back.
difftimedouble difftime ( time_t time2, time_t time1 );Returns the time difference between time1 and time2.
mktimetime_t mktime(struct tm *time);Changes the tm structure to the time_t format or the equivalent calendar format.
Date & Time Functions In C++ With Examples

Programming Example

The following code example calculates the current time in local and GMT format and displays it.

#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;
 }

Program Explanation

The time function is used in the above example to get the current time, which is then formatted as a string.

In the same way, it gets GMT using the “gmtime” function and turns it into a string using the “asctime” function.

Later, it tells the user what time it is in GMT.

 Output:

Here is the output:

The current local date and time is: Wed Aug  3 07:19:31 2022
The current UTC date and time is: Wed Aug  3 07:19:31 2022

How can I get the current time and date in C++?

Here is an example to get the current date and time in the C++ language:

#include <iostream>
#include <ctime>

using namespace std;

int main() {
   // current date/time based on current system
   time_t now = time(0);
   
   // convert now to string form
   char* dt = ctime(&now);

   cout << "The local date and time is: " << dt << endl;

   // convert now to tm struct for UTC
   tm *gmtm = gmtime(&now);
   dt = asctime(gmtm);
   cout << "The UTC date and time is:"<< dt << endl;
}

Explanation

The code to get the current date and time is in the main() section of the above program.

In this case, the return type of variable now is time_t. The current time and date are found using the built-in function time().

Output

Here is the output:

The local date and time is: Wed Aug  3 07:18:32 2022

The UTC date and time is: Wed Aug  3 07:18:32 2022

Format Time using struct tm

When working with dates and times in C or C++, the tm structure is very important.

As was said above, this structure holds the date and time in the form of a C structure.

tm structure is used most of the time by functions that are related to each other.

When I use structure in this chapter, I assume you know the basics of C structure and how to use the arrow -> operator to get to structure members.

Program Example

Following is an example that makes use of various date and time-related functions and tm structure −

#include <iostream>
#include <ctime>

using namespace std;

int main() {
   // current date/time based on current system
   time_t now = time(0);

   cout << "Number of sec since January 1,1990 is:: " << now << endl;

   tm *ltm = localtime(&now);

   // print various components of tm structure.
   cout << "Year:" << 1900 + ltm->tm_year<<endl;
   cout << "Month: "<< 1 + ltm->tm_mon<< endl;
   cout << "Day: "<< ltm->tm_mday << endl;
   cout << "Time: "<< 5+ltm->tm_hour << ":";
   cout << 30+ltm->tm_min << ":";
   cout << ltm->tm_sec << endl;
}

Output:

When the above code is compiled and executed, it produces the following result.

Number of sec since January 1,1990 is: : 1659511243
Year: 2022
Month: 8
Day: 3
Time: 12:50:43

Explanation

As the above output shows, we got the local time and then showed the year, month, day, and time in the format of “hour: minutes: seconds.”

Conclusion

In summary, the main focus of this session, C++ Date and Time Functions with Examples was to get deeper into what C++ is: Std::ctime, its type, and the “tm” structure, as well as example programs of date and time functions in C++.

Furthermore, we tackled Format Time using struct tm and its example program with output and explanation.

That’s it! The C++ Date and Time Functions with Examples is now complete! 

Even though it’s a small topic, it’s very important to our understanding of the C++ Programming Tutorial.

You did great to finish this session.

Leave a Comment