#This is a homework assignment#

I need to calculate how many seconds old I am in C. I'm thinking that I can take my birthday as user input and convert it to a date with strptime. I then would like to take the present date and put both it and my birthday into seconds or unix time. Then it's just a matter of subtraction to get the right output. The code below takes the command line parameters: mm dd yyyy, puts them(I think) attempts to convert it to a date recognized by the tm_structure and then print it. It fails with the output Your Birthday is: (null) Any input on how to fix this would be of great help. Also, any suggestions if there is a more efficient way to do this would also be of great help.

Thanks
P.S. I'm a beginner

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

int main(int argc, char *argv[]) {

  char *month, *day, *year;
  char buf[256];
  int result;
  struct tm *tm_ptr;
      time_t the_time;

      month = argv[1];
      day = argv[2];
      year = argv[3];

      strcpy(buf, month);  
      strcat(buf, " ");
      strcat(buf, day);
      strcat(buf, " ");
      strcat(buf, year);
      
      result = strptime(buf,"Today is %m %d %Y.\n", the_time);
      printf("Your Birthday is: %s\n", result);
  
      (void) time(&the_time);
      tm_ptr = gmtime(&the_time);
      printf("Current time in seconds is: %ld\n", the_time);
  
   return 0;
}

Recommended Answers

All 22 Replies

Made some changes to the code. I'm now getting "Your Birthday is: 0" instead of "(null)." I really don't understand a whole lot about how struct_tm works. I've just been looking at different examples in my text book and trying to make it work.

Updated Code:

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

int main(int argc, char *argv[]) {

  char *month, *day, *year;
  char buf[256];
  char result;
  struct tm *tm_ptr;
      time_t the_time;

      month = argv[1];
      day = argv[2];
      year = argv[3];

      strcpy(buf, month);  
      strcat(buf, " ");
      strcat(buf, day);
      strcat(buf, " ");
      strcat(buf, year);
      
      (void) time(&the_time);
      tm_ptr = gmtime(&the_time);
      result = strptime(buf,"Today is %m %d %Y.\n", the_time);
      printf("Your Birthday is: %ld\n", result);
      printf("Current time in seconds is: %ld\n", the_time);
  
  return 0;
}

I don't have that strptime() function, so I suggest:

1) Use an unsigned long for the seconds' data type. Int may over-run.

2) Once you get the number of days, (or whatever units you want to work with, just do the math yourself:

seconds +=hoursPerDay * secondsPerHour, + etc.

Ok, what do you mean by an unsigned long for seconds data type? Are you saying that I should use the int tm_sec instead of the_time?

seconds +=hoursPerDay * secondsPerHour, + etc.

OK, I think I see what you mean.

I'm saying I don't see how it can be right to print out result (which is?? the final answer in seconds I think), using %ld in printf().

Result is a char, and char's have a very small maximum value.

I'm approaching this from a "get the number of days, hours, minutes and seconds, and convert that entire amount to seconds", POV.

OK, I understand what your saying but I'm not sure how to fix it. my goal is to have two dates, the present and a birthdate and then get the seconds in between them.

I'm approaching this from a "get the number of days, hours, minutes and seconds, and convert that entire amount to seconds", POV.

I get that part but doesn't I need my input to be formatted before i can do that?

Work it out, step by step. First, can you get the number of years, correctly?

What about the number of months, after the last full year?

Then get the number of days, after the last full month.

You see where I'm going with this: step by step, large to small:
The number of hours past the last full day,
The number of minutes after the last full hour
and lastly, the number of seconds after the last full minute.

Where are you stuck? ;)

OK, are you looking to use difftime() ?

Here's an example, but I'm not exactly sure how it could fit into what you're doing - but it's very possible. ;)

#include <time.h>
#include <stdio.h>
#include <dos.h>
int main(void)
{
   time_t first, second;

   first = time(NULL);  /* Gets system
                           time */
   delay(2000);         /* Waits 2 secs */
   second = time(NULL); /* Gets system time
                           again */

   printf("The difference is: %f seconds\n",difftime(second,first));
   getch();

   return 0;
}

Work it out, step by step. First, can you get the number of years, correctly?

What about the number of months, after the last full year?

Then get the number of days, after the last full month.

You see where I'm going with this: step by step, large to small:
The number of hours past the last full day,
The number of minutes after the last full hour
and lastly, the number of seconds after the last full minute.

Where are you stuck? ;)

Alright, I'm getting there :)

#include <stdio.h>
int main()
{
    int age;
    int present;
    int seconds;
    int answer;
    present=2011;
    seconds=31556926;
    printf("enter the year you where born:");
    scanf("%d",&age);
    answer = ((present-age) * seconds); 
    printf("You are %d seconds old.\n",answer);
    
    return(0);
}

Nope, on second thought I don't think difftime() is what you want. In my (old) compiler, I'd use two structs called "tm" (included in time.h). One would get my birthday data, the second one would get filled in by C itself, for now.

Then it's a matter of a little arithmetic, subtracting one tm struct members, from the other, and a bit of arithmetic on the resulting answer, and it's done. The big advantage of using the tm struct, is that the data is nicely laid out for you, for the current date/time, with it.

Let me know if you want to work with the tm struct, and need the struct definition, etc.

Sorry to confuse you, but I haven't done this kind of a program in a very long time. Lots of rust. ;)

OK, we can go this way, also.

A couple defines (or just data), to keep in mind:
SECSinHOUR 3600
SECSinDAY 86400

These are the leap years we need to work with:

1972
1976
1980
1984
1988
1992
1996
2000
2004
2008

Here's the new code. How do I get from 2011(as present time) to the current date and from 1995 to a date like 2/8/1995?

darn, I forgot about leap years :(

#include <stdio.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[]) {
  char *month, *day, *year;
  char buf[256];
  int dob;
  int present;
  int seconds;
  int answer;
    
    month = argv[1];
    day = argv[2];
    year = argv[3];
  
    strcpy(buf, month);  
    strcat(buf, " ");
    strcat(buf, day);
    strcat(buf, " ");
    strcat(buf, year);
  
  struct tm *tm_ptr;
    time_t the_time;
  (void) time(&the_time);
    tm_ptr = gmtime(&the_time);
    printf("current time in seconds: %ld\n", the_time); //accurate unix time
    printf("My Birthday: %s\n", buf); //user input from argv
    
    present=2011;
    seconds=31556926;
    printf("enter the year you where born:");
    scanf("%d",&dob);
    answer = ((present-dob) * seconds); 
    printf("You are %d seconds old.\n",answer); //seconds from 1995 to 2011
  return(0);
}

You need to stop thrashing about just trying things, and not understanding what you are using. Everything you need is in the time.h header. Find an explanation of the functions and structures it contains (GOOGLE) and read it. Then you will be able to do this task with ease. It's just a matter of calling the correct function to get your birthday value and subtract it from your TODAY value.

If you want to use tm, the system will handle leap years extra day, for you, IIRC.
Look at your help for the tm struct, and you'll see what you need to fill out. For my (older) struct, the tm is like this:

struct tm {
    int  tm_sec,  tm_min,  tm_hour;
    int  tm_mday, tm_mon,  tm_year; 
    int  tm_wday, tm_yday;
    int  tm_isdst;
  };

mday is "day of the month", 1-31.
wday is "day of the week" Sunday is 0
yday is "day of the year" 1-366
isdst is "is Daylight Saving Time, in your local time zone? 0 No or 1,Yes

Your answer can't be an int - (depending on your system and age, of course), make it an unsigned long int, if needed.

difftime returns the difference in seconds:

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

time_t get_date(int year, int month, int day)
{
    time_t start = time(NULL);
    struct tm *date = localtime(&start);

    date->tm_year = year - 1900;
    date->tm_mon = month - 1;
    date->tm_mday = day;

    return mktime(date);
}

int main(void)
{
    time_t bday = get_date(1978, 11, 11);
    time_t now = time(NULL);

    if (bday != -1 && now != -1)
        printf("You are %.0f seconds old\n", difftime(now, bday));

    return 0;
}

That should get you close enough to tweak the result.

There we go! Thanks, Narue. I'd mentioned difftime(), but veered away from it because I didn't think it would handle years and leap years.

Heads up, Nick! ;)

Or, since now and bday are both in seconds, use subtraction rather than calling a function.

Or, since now and bday are both in seconds, use subtraction rather than calling a function.

now and bday are both time_t. Arithmetic isn't portable, which is why difftime exists in the first place.

Alright, I tried this but it's still not working. Could someone explain what I'm doing wrong?

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

time_t get_date(int year, int month, int day)
{
    time_t start = time(NULL);
    struct tm *date = localtime(&start);

    date->tm_year = year - 111;
    date->tm_mon = month - 1;
    date->tm_mday = day - 6;

    return mktime(date);
}

int main(void)
{
    time_t bday = get_date(1995, 2, 8);
    time_t now = time(NULL);

    if (bday != -1 && now != -1)
        printf("You are %.0f seconds old\n", difftime(now, bday));

    return 0;
}

time(NULL) gives you the current date.

Alright, I finally got it working. I got to say thanks to Narue and to Adok!

Here's the working code:

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

time_t get_date(int year, int month, int day, int hour, int min, int sec)
{
    time_t start = time(NULL);
    struct tm *date = localtime(&start);

    date->tm_year = year - 1900;
    date->tm_mon = month - 1;
    date->tm_mday = day;
    date->tm_hour = hour;
    date->tm_min = min;
    date->tm_sec = sec;
    return mktime(date);
}

int main(void)
{
    time_t bday = get_date(1995, 2, 8, 12, 0, 0);
    time_t now = time(NULL);

    if (bday != -1 && now != -1)
        printf("You are %.0f seconds old\n", difftime(now, bday));

    return 0;
}

Man, I feel dumb right now....o well, another piece of code I can tuck away for later reference....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.