asctime() Function Example in C Programming

In this source code example, we will see how to use the asctime() function in C programming with an example.

asctime() Function Overview

The asctime() function in C is used to convert a given time structure (struct tm) into a string format representing the time. The resulting string has a format that looks like this: "Day Mon Date Hours:Minutes:Seconds Year". This function is part of the time.h library. 

Key Points: 

- The time.h header is essential to utilize asctime()

- It accepts a pointer to a struct tm as its parameter. 

- The function returns a pointer to a string representation of the time. 

- The returned string is stored in a static buffer, which gets overwritten with subsequent calls. Therefore, it's important to save or use the result immediately after calling asctime().

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for gmtime(), asctime(), and struct tm

int main() {
    time_t current_time;
    struct tm *time_info;
    char *time_str;

    // Capture the current calendar time
    time(&current_time);

    // Convert the current time to a struct tm
    time_info = gmtime(&current_time);

    // Convert the struct tm to a string format
    time_str = asctime(time_info);

    printf("The current UTC time in string format is: %s", time_str);

    return 0;
}

Output

The current UTC time in string format is: Sun Apr 30 14:27:29 2023
(Note: The exact output will differ based on when the program is executed.)

Explanation

1. We start by including the necessary header files: stdio.h for input/output operations and time.h for gmtime(), asctime(), and the definition of struct tm.

2. Inside the main() function, we first obtain the current calendar time in time_t format.

3. We utilize the gmtime() function to convert this time_t value into a struct tm representing UTC.

4. Subsequently, the asctime() function is used to transform the struct tm into its string representation.

5. Finally, we print this string representation to the console.

The asctime() function is handy when there's a need for a quick and readable string representation of a date and time, especially for display purposes or logging.


Comments