localtime() function in C++

In this guide, you will learn what is localtime() function is in C++ programming and how to use it with an example.

1. localtime() Function Overview

The localtime() function in C++ is used to convert a given time_t value into a tm structure that represents the local time (i.e., considering the current time zone). The structure provides individual fields for various components like year, month, day, hour, minute, and second. The function is part of the <ctime> header.

Signature:

struct tm* localtime(const time_t* timer);

Parameters:

- timer: Pointer to a time_t value representing the number of seconds elapsed since the epoch (00:00:00, January 1, 1970, Coordinated Universal Time).

2. Source Code Example

#include <iostream>
#include <ctime>

int main() {
    std::time_t t;
    std::time(&t);

    // Convert time_t value to local time
    struct tm* local_time = localtime(&t);

    std::cout << "Current Year: " << (local_time->tm_year + 1900) << std::endl; // tm_year is years since 1900
    std::cout << "Current Month: " << (local_time->tm_mon + 1) << std::endl;   // tm_mon is in range [0, 11]

    return 0;
}

Output:

Current Year: yyyy  (e.g., 2023)
Current Month: mm  (e.g., 8)

3. Explanation

1. We first capture the current time using the time() function and store it in a time_t variable.

2. The localtime() function is used to convert this time_t value into a tm structure representing the local time.

3. We then access individual fields of this structure to print the current year and month. Notably, the year is represented as years since 1900, and the month is represented as an index starting from 0 for January.


Comments