C Program to Print Current Date and Time

Quite often we need to print the current date and time from our program. For example, when we write log messages, we generally attach the timestamp with every message. Here we’ll see how to write a C program to print the current date and time.

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

int main(){
  
  char cur_time[128];
  
  time_t      t;
  struct tm*  ptm;
  
  t = time(NULL);
  ptm = localtime(&t);
    
  strftime(cur_time, 128, "%d-%b-%Y %H:%M:%S", ptm);
  
  printf("Current date and time: %s\n", cur_time);
  
  return 0;
}

The time() function returns the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). Function localtime() takes this number and converts it in broken-down time structure. Broken-down time, which is stored in the structure ptm, looks like:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

The strftime() function formats the broken-down time tm according to our format specification, “%d-%b-%Y %H:%M:%S”.

Output of the program:

Current date and time: 25-Aug-2019 21:45:39

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

3
2
1
4
10
6