w3resource

C Exercises: Convert a time_t object to a textual representation


3. time_t to Textual Representation

Write a program in C to convert a time_t object to a textual representation.

Sample Solution:

C Code:

#define __STDC_WANT_LIB_EXT1__ 1 // Enable safer C library functions
#include <time.h>
#include <stdio.h>

int main(void) {
    time_t result = time(NULL); // Get the current calendar time (in seconds since epoch) and store it in 'result'
    printf("\n%s\n", ctime(&result)); // Print the string representation of the calendar time 'result'

#ifdef __STDC_LIB_EXT1__
    char time_str[26]; // Declare an array of characters to hold the time string with space for null-terminator
    ctime_s(time_str, sizeof time_str, &result); // Safer version of ctime() to prevent buffer overflow
    printf("\n%s\n", time_str); // Print the safer time string 'time_str'
#endif
}

Output:

Thu Aug 03 13:44:49 2017

N.B.: The result may varry for your current system date and time.

Flowchart:

Flowchart: Convert a time_t object to a textual representation


For more Practice: Solve these Related Problems:

  • Write a C program to convert a time_t object to a formatted string in ISO 8601 standard format.
  • Write a C program that takes a time_t object and outputs its textual representation including the time zone abbreviation.
  • Write a C program to convert a time_t object to a textual representation and also display the difference from the current time.
  • Write a C program to format a time_t object into a human-readable string that includes the full date and time details.

Go to:


PREV : Seconds Since Month Start.
NEXT : tm Object Custom Text Format.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.