C++ Date & Time


Almost every program needs to work with time or dates in some way. Whether it’s displaying the current time, calculating the difference between two dates, or logging when an event occurred, C++ provides built-in tools to handle these tasks easily.

C++ includes the <ctime> library (also known as <time.h> in C) that allows you to get and manipulate date and time information. It includes functions to fetch the current time, format it into readable text, and perform time-based calculations.

The ctime Library

To use date and time functions in C++, you need to include the following header:

#include <iostream>
#include <ctime>
using namespace std;

This library gives access to several useful types and functions, such as:

  • time_t – stores time as a numeric value.

  • tm – a structure that stores broken-down time like hours, minutes, and seconds.

  • time() – returns the current time as the number of seconds since January 1, 1970 (known as the epoch).

  • localtime() – converts the time to your local time zone.

  • asctime() – converts a tm structure into a readable string.

Getting the Current Date and Time

The simplest way to display the current date and time is by using the time() and ctime() functions.

Example:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t currentTime;
    time(&currentTime);   // get current time
    cout << "Current date and time: " << ctime(&currentTime);
    return 0;
}

The ctime() function automatically converts the time to a human-readable format like:

Current date and time: Wed Oct 29 14:25:03 2025

Using struct tm for Detailed Time Information

The tm structure in C++ breaks time into components such as seconds, minutes, hours, day, month, and year.

Example:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(0);
    tm *ltm = localtime(&now);

    cout << "Year: " << 1900 + ltm->tm_year << endl;
    cout << "Month: " << 1 + ltm->tm_mon << endl;
    cout << "Day: " << ltm->tm_mday << endl;
    cout << "Time: " << 1 + ltm->tm_hour << ":" << 1 + ltm->tm_min << ":" << 1 + ltm->tm_sec << endl;

    return 0;
}

This gives a clear breakdown of the current local date and time.

Formatting the Date and Time

Sometimes, you may want to display the date in a specific format like “DD-MM-YYYY” or “HH:MM:SS”. For that, C++ provides the strftime() function, which formats the date and time according to your choice.

Example:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(0);
    tm *ltm = localtime(&now);

    char formatted[80];
    strftime(formatted, 80, "%d-%m-%Y %H:%M:%S", ltm);
    cout << "Formatted Date and Time: " << formatted;
    return 0;
}

Here, %d means day, %m means month, %Y is the year, and %H:%M:%S represent hours, minutes, and seconds respectively.

Measuring Execution Time of Code

If you want to check how long a block of code takes to run, you can use the clock() function.

Example:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    clock_t start = clock();

    for (int i = 0; i < 1000000; i++); // time-consuming loop

    clock_t end = clock();
    double timeTaken = double(end - start) / CLOCKS_PER_SEC;
    cout << "Execution time: " << timeTaken << " seconds.";
    return 0;
}

This helps measure performance and optimize slow sections of your program.

Calculating Time Difference

You can also calculate the time difference between two moments using the difftime() function.

Example:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t start, end;
    time(&start);
    cout << "Waiting for 3 seconds..." << endl;
    sleep(3);
    time(&end);

    double difference = difftime(end, start);
    cout << "Time elapsed: " << difference << " seconds." << endl;
    return 0;
}

This program pauses for three seconds and then calculates the time elapsed.

Working with UTC Time

If you want to handle Coordinated Universal Time (UTC), use the gmtime() function instead of localtime().

Example:

#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(0);
    tm *gmt = gmtime(&now);
    cout << "UTC Time: " << asctime(gmt);
    return 0;
}

Commonly Used Time Formatting Symbols

Symbol Meaning
%d Day of the month (01–31)
%m Month (01–12)
%Y Year (e.g., 2025)
%H Hour (00–23)
%M Minute (00–59)
%S Second (00–59)
%a Abbreviated weekday name
%b Abbreviated month name

Summary of C++ Date and Time

The <ctime> library in C++ makes it easy to work with date and time. You can display the current time, extract specific components using tm, format the output using strftime(), and calculate time differences. Understanding date and time handling is essential for creating logs, timestamps, and time-based applications.


Practice Questions

  1. Write a C++ program that displays the current date and time using the ctime() function.

  2. Create a program that extracts and prints the current year, month, and day separately using the tm structure.

  3. Write a C++ program to display the current time in the format HH:MM:SS.

  4. Develop a program that prints the date in the format DD-MM-YYYY.

  5. Write a program to calculate the time taken by a loop to execute using the clock() function.

  6. Create a program that pauses execution for 5 seconds using sleep() and then displays the time difference using difftime().

  7. Write a program that displays both the local time and UTC (GMT) time on the screen.

  8. Develop a program that shows the current day of the week (like Monday, Tuesday, etc.) using strftime().

  9. Create a program that takes a specific date and converts it into a timestamp (seconds since epoch).

  10. Write a C++ program that repeatedly displays the current time every second for 10 seconds like a digital clock.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top