Related Tags

c++
current
date
time

# How to get the current date and time in C++

A lot of programming tasks require the current date and time for processing. In C++, this can be done using the following two methods:

## 1. time

This method returns the current calendar time of the system in number of seconds elapsed since January 1, 1970​. If the system has no time, the ​function returns a value of -1.

### Syntax

See the function definition of the time method below:

The time_t data type represents the system time and date as an integer.

## 2. ctime

This method returns a pointer to a string that holds the date and time in the form of $day$ $month$ $year$ $hours:minutes:seconds$.

## Code

The code snippet (below) illustrates the usage of the two functions (above) ​to get the current date and time in C++:

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

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

// convert now to string form
char* date_time = ctime(&now);

cout << "The current date and time is: " << date_time << endl;
}

RELATED TAGS

c++
current
date
time