Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Print Current Date and Time

$
0
0

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

The post C Program to Print Current Date and Time appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>