Cory Allen
Cory Allen

Reputation: 159

Time not printing on command line when compiled

I'm trying to run the below code. I'm compiling like so.

gcc -o time time.c

Instead of getting my desired output, the current time of day, hor minute, year, etc.

Today is : Thu Oct 31 02:01:37 2019
Time is : 02:01:37 am
Date is : 31/10/2019

I'm getting this instead. I've tried a variety of different time functions similar to this and I keep getting this below output instead of what I want.

real    0m0.000s
user    0m0.000s
sys     0m0.000s

I'm sure this is really simple, can anyone point me in the right direction?

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

// Print current date and time in C
int main(void){
   // variables to store date and time components
   int hours, minutes, seconds, day, month, year;

   // time_t is arithmetic time type
   time_t now;

   // Obtain current time
   // time() returns the current time of the system as a time_t value
   time(&now);

   // Convert to local time format and print to stdout
   printf("Today is : %s", ctime(&now));

   // localtime converts a time_t value to calendar time and 
   // returns a pointer to a tm structure with its members 
   // filled with the corresponding values
   struct tm *local = localtime(&now);

   hours = local->tm_hour;          // get hours since midnight (0-23)
   minutes = local->tm_min;         // get minutes passed after the hour (0-59)
   seconds = local->tm_sec;         // get seconds passed after minute (0-59)

   day = local->tm_mday;            // get day of month (1 to 31)
   month = local->tm_mon + 1;       // get month of year (0 to 11)
   year = local->tm_year + 1900;    // get year since 1900

   // print local time
   if (hours < 12)  // before midday
      printf("Time is : %02d:%02d:%02d am\n", hours, minutes, seconds);

   else // after midday
      printf("Time is : %02d:%02d:%02d pm\n", hours - 12, minutes, seconds);

     // print current date
     printf("Date is : %02d/%02d/%d\n", day, month, year);

     return 0;
}

Upvotes: 0

Views: 128

Answers (1)

Acorn
Acorn

Reputation: 26166

It seems to me you are calling the time command somehow, rather than your program.

Typically you will want to do:

./time

Instead of:

time

Upvotes: 1

Related Questions