w3resource logo


C Programming Exercises

C Exercises: Print the current time

Secondary Nav

C Date Time: Exercise-1 with Solution

Write a program in C to print the current time.

Expected Output :

The Current time is : Tue Sep  6 11:47:52 2016

C Code:

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

int main(void)
{
    time_t cur_time;
    char* cur_t_string;
    cur_time = time(NULL);
    if (cur_time == ((time_t)-1))
    {
        (void) fprintf(stderr, "Failure to get the current time.\n");
        exit(EXIT_FAILURE);
    }
    cur_t_string = ctime(&cur_time); //convert to local time format
    if (cur_t_string == NULL)
    {
        (void) fprintf(stderr, "Failure to convert the current time.\n");
        exit(EXIT_FAILURE);
    }
    (void) printf("\n The Current time is : %s \n", cur_t_string);
    exit(EXIT_SUCCESS);
}

Flowchart :

Flowchart: Print the current time

C Practice online:

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

int main(void)
{
    time_t cur_time;
    char* cur_t_string;
    cur_time = time(NULL);
    if (cur_time == ((time_t)-1))
    {
        (void) fprintf(stderr, "Failure to get the current time.\n");
        exit(EXIT_FAILURE);
    }
    cur_t_string = ctime(&cur_time); //convert to local time format
    if (cur_t_string == NULL)
    {
        (void) fprintf(stderr, "Failure to convert the current time.\n");
        exit(EXIT_FAILURE);
    }
    (void) printf("\n The Current time is : %s \n", cur_t_string);
    exit(EXIT_SUCCESS);
}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program