localtime() function in C++ with an example

In this tutorial, we will learn about what is localtime() function in c++ is, we want to make this tutorial easy to understand for you and learn in-depth concepts of such function in c++.

So, I am going to make this tutorial interesting for you and I hope you also you are excited to see how we can make use of the localtime() function and this functionality is useful to include in your projects.

About localtime() in C++

localtime() function is defined under ctime header file.

Defined in header <ctime>

The functionality of loacaltime() is to convert a given time epoch(a particular period in history) into a calendar time(local time). In nature, this function may not be thread-safe.


tm* localtime(const time_t* time_pointer);

Now, understand what is above code specifies. So, localtime() takes argument time_t type as a pointer. On success returns a pointer object tm and on failure, it returns a NULL pointer. Access the hours, minutes as well seconds can be done by using tm_hour, tm_min, and tm_sec respectively.

POSIX requires the localtime() function sets errno to EOVERFLOW  in case it fails because of the passing argument which can be too large.

Sample code:

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

int main()
  time_t currentTime;
  currentTime = time(NULL);

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


Current local time : 18:23:22

Hope you liked this tutorial. Do share with your friends.

Also read: C++ time() function with example

Leave a Reply

Your email address will not be published. Required fields are marked *