C++ localtime()

The localtime() function is defined in <ctime> header file.

localtime() prototype

tm* localtime(const time_t* time_pretr);

The localtime() function takes a pointer of type time_t as its argument and returns a pointer object of structure tm. The value returned by localtime() function is the local time.

Then, the hours, minutes and seconds can be accessed using tm_hour, tm_min and tm_sec respectively.


localtime() Parameters

  • time_ptr: pointer to a time_t object to be converted.

localtime() Return value

  • On success, the localtime() function returns a pointer to a tm object.
  • On failure, a null pointer is returned.

Example: How localtime() function works?

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

int main()
{
	time_t curr_time;
	curr_time = time(NULL);

	tm *tm_local = localtime(&curr_time);
	cout << "Current local time : " << tm_local->tm_hour << ":" << tm_local->tm_min << ":" << tm_local->tm_sec;
	return 0;
}

When you run the program, the output will be:

Current local time : 19:20:14

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges