asctime_r - Linux


Overview

asctime_r formats a time, expressed as the standard C struct tm, into a string representation in a standard format. It’s particularly useful when customizing data and time output.

Syntax

#include <time.h>

char *asctime_r(const struct tm *timeptr, char *buf);

Arguments

  • timeptr: Pointer to the struct tm containing the time to be formatted.
  • buf: Buffer to store the formatted time string. It should have at least 26 bytes allocated.

Options/Flags

None

Examples

Example 1: Basic usage

#include <stdio.h>
#include <time.h>

int main() {
    struct tm time;
    char buf[26];
    time_t current_time = time(NULL);
    gmtime_r(&current_time, &time);
    asctime_r(&time, buf);
    printf("Current time in UTC: %s", buf);
    return 0;
}

Example 2: Formatting a specific time

#include <stdio.h>
#include <time.h>

int main() {
    struct tm time;
    char buf[26];
    time.tm_year = 2023 - 1900; // Years since 1900
    time.tm_mon = 5 - 1; // Months since January (0-indexed)
    time.tm_mday = 15;
    time.tm_hour = 10;
    time.tm_min = 30;
    time.tm_sec = 0;
    asctime_r(&time, buf);
    printf("Formatted time: %s", buf);
    return 0;
}

Common Issues

  • Buffer size: Ensure the buf has enough allocated space, at least 26 bytes, to store the formatted time string.
  • Thread safety: asctime_r is thread-safe, but asctime is not. If multiple threads access the same struct tm concurrently, use asctime_r.

Integration

asctime_r can be used with other time-related functions, such as:

  • gmtime_r: Convert a time value to a Coordinated Universal Time (UTC) struct tm.
  • localtime_r: Convert a time value to a local struct tm.

Related Commands

  • ctime: Formats a time_t value into a string using the standard asctime function.
  • strftime: Formats a struct tm into a string using a user-defined format string.