Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
current
date
time

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

Educative Answers Team

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:

svg viewer

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 dayday monthmonth yearyear hours:minutes:secondshours:minutes:seconds.

Syntax

svg viewer

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
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring