Get date and time by C program

In this C programming guide you will learn to print date and time by C in different format. Let’s see the default format of print date and time in C.

Get current date and time in default format

Here we have used time_t to store system’s current time which is a data type taken from ISO library. The standard time() function which is defined under time.h header file returns the system time and we store it to time_t. ctime() functon returns a string representing local time. It is also defined under time.h header file.

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

int main(){
    
  time_t present_time;
  
  time(&present_time);
  
  printf("\n\n------------------Now Time--------------------\n\n");
  
  printf("\t%s", ctime(&present_time));
  
  printf("\n\n----------competitiveprogrammer.com-----------\n\n");
  
  getch();
  return 0;
}

Output of date and time program:

get-date-and-time-in-c-c-program-to-get-date-and-time

Get date in (dd-mm-yyyy) format

#include <stdio.h>
#include <conio.h>
#include <time.h>
int main(){
  time_t current_time;

  current_time = time(NULL);

  struct tm tm = *localtime(&current_time);

  printf("\n\n----------------Today's Date------------------\n\n");

  printf("\t\t%d-%d-%d", tm.tm_mday, tm.tm_mon + 1, tm.tm_year + 1900);

  printf("\n\n----------competitiveprogrammer.com-----------\n\n");

  getch();
  return 0;
}

Output of this get date program:

----------------Today's Date------------------

                12-7-2021

----------competitiveprogrammer.com-----------

Get time in (hh:mm:ss) format

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

int main(){
  time_t now_time;

  now_time = time(NULL);

  struct tm tm;

  tm = *localtime(&now_time);

  printf("\n\n------------------Now Time--------------------\n\n");

  printf("\t\t%d : %d : %d", tm.tm_hour, tm.tm_min, tm.tm_sec);

  printf("\n\n----------competitiveprogrammer.com-----------\n\n");

  getch();
  return 0;
}

Output:

------------------Now Time--------------------

                18 : 23 : 38

----------competitiveprogrammer.com-----------

When you compile and run these program, you will get your current time. Your output will be different from us because these functions will print your current time. So, don’t worry.

Previous pageRandom numbers

Next pagePrint IP address