ctime

Given day, month, year calculate day in year


I'am finished with the first half. Validating the input. Now I need to calculate the day in year regarding my input.

My idea is to use the time.h library and somehow send my input to it and get back the given day in the year. My problem is I don't understand how it works or if my idea is working at all.

Any help is appreciated.

Thank you!

    /* 
Uebung 2 - 
Aufgabe 1
*/

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

int dd = 0;
int mm = 0;
int yy = 0;

int main()
{ 
   printf("Bitte geben Sie ein Datum in folgenden Format ein dd.mm.yyyy: ");
   scanf("%d.%d.%d", &dd, &mm, &yy);

   //check year
   if (yy>=1900 && yy<=9999)
   {
      //check month
      if(mm>=1 && mm<=12)
      {
         //check days
         if((dd>=1 && dd<=31) && (mm==1 || mm==3 || mm==5 || mm==7 || mm==8 || mm==10 || mm==12 ))
            printf("Datum richtig!\n");
         else if((dd>=1 && dd<=30) && (mm==4 || mm==6 || mm==9 || mm==11))
            printf("Datum richtig!\n");
         else if((dd>=1 && dd<=28) && (mm==2))
            printf("Datum richtig!\n");
         else if(dd==29 && mm==2 && (yy%400==0 || (yy%4==0 && yy%100!=0)))
            printf("Datum richtig!\n");
         else
            printf("Eingabe Tag falsch.\n");
      }
      else
      {
         printf("Eingabe Monat falsch.\n");
      }
   }
   else
   {
      printf("Eingabe Jahr falsch.\n");
   }
   printf("Folgendes Datum wurde eingelesen: %d.%d.%d\n", dd, mm, yy);
   return 0;
}

Solution

  • You can create a struct tm structure, and set the fields all zero:

    struct tm t1 = { 0 };
    

    and then set the tm_year, tm_mon, tm_mday fields carefully, noting that you have to subtract 1900 from the year and 1 from the month. Set the tm_isdst field to -1. Then call mktime() and extract the value you need from tm_yday (0 for 1st January to 364 or 365 for 31st December).

    int day_of_year(int year, int month, int day)
    {
        struct tm t1 = { 0 };
        t1.tm_year = year - 1900;
        t1.tm_mon  = month - 1;
        t1.tm_mday = day;
        t1.tm_isdst = -1;
        mktime(&t1);
        return t1.tm_yday + 1;
    }
    

    This returns a number 1..366 for the day of the year. It doesn't directly validate the presented year, month, day values, but mktime() 'normalizes' those values. The mktime() function does report errors by returning -1; I've ignored that.