asctime() function in C++

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

1. asctime() Function Overview

The asctime() function in C++ is utilized to convert a tm structure into a human-readable string representing the date and time. The resulting string has the format: "Www Mmm dd hh:mm:ss yyyy", where "Www" is the weekday, "Mmm" the month, "dd" the day of the month, "hh:mm:ss" the time, and "yyyy" the year. The function is a part of the <ctime> header file.

Signature:

const char* asctime(const struct tm* timeptr);

Parameters:

- timeptr: Pointer to a tm structure representing local time.

2. Source Code Example

#include <iostream>
#include <ctime>

int main() {
    std::time_t t;
    std::time(&t);
    struct tm* timeinfo;

    // Convert time_t to tm struct
    timeinfo = std::localtime(&t);

    // Convert tm structure to human-readable string
    std::cout << "Current date and time: " << asctime(timeinfo);

    return 0;
}

Output:

Current date and time: Www Mmm dd hh:mm:ss yyyy

3. Explanation

1. Obtain the current time using the time() function and store it in a variable of type time_t.

2. Convert this time_t value to a tm structure using the localtime() function.

3. Utilize the asctime() function to convert this tm structure into a human-readable string format.

4. Print the obtained string, which represents the current date and time, to the console.


Comments