Mega Code Archive

 
Categories / C / Development
 

Getting the time as a string

#include <stdio.h> #include <time.h> #include <string.h> #define TIME_24   1 #define TIME_12   0 char *get_time_string(int mode24);     /* Returns the time as a string in 12 or 24 hour format */ int main() {   char time_str[12];   get_time_string(TIME_24);   printf("\n\n");   get_time_string(TIME_12); } char* get_time_string(int mode24) {   static char time_str[12] = {0};   /* Stroes the time as a string */   struct tm *now = NULL;   int hour = 0;   time_t time_value = 0;   time_value = time(NULL);          /* Get time value              */   now = localtime(&time_value);     /* Get time and date structure */   hour = now->tm_hour;              /* Save the hour value         */   if(!mode24 && hour>12)            /* Adjust if 12 hour format    */     hour -= 12;   printf("%d:",hour);   printf("%d:",now->tm_min);   printf("%d",now->tm_sec);   if(!mode24)     if(now->tm_hour>24){        printf("PM\n");     }else{        printf("AM\n");      }   return time_str; }