PnP
PnP

Reputation: 3185

C - calculate all dates from Year X to Year Y

Please IGNORE, incompetence as its best!

Just messing with some basic file i/o really, in some nested for Loops but the output isn't quite what I want, though I can't seem to get it working.

#include <stdio.h>

int main(void) {
FILE *pFile;
pFile = fopen("dates.txt", "w");
int day, month, year;
for(day = 1; day <= 31; day++) {
 for(month = 1; month <= 12; month++) {
   for(year = 1900; year <= 2050; year++) {
 if(day < 10 && month < 10) {
   fprintf(pFile, "0%d/0%d/%d\n", day, month, year);
 }else {
   fprintf(pFile, "%d/%d/%d\n", day, month, year);
 }
   }
 }
 }
 return 0;
}

Any tips much appreciated! And as a heads up, this isn't an homework task, just some experimentation really.

Cheers.

Upvotes: 0

Views: 161

Answers (3)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

You can use mktime to create a date. Then add 1 day to it and create the next date. This way you can iterate.

Following code shows first 200 dates.

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

int main(){
    struct tm *lt;

    int i=200;

//time_t t=0;  // first second on epoch
    time_t t=-2209010000; // first second on 1900 (works on GCC, dind't test MSVS compiler)

    while(i--){
        lt = localtime(&t);
        printf("YYYY:MM:DD = %04d:%02d:%02d\n", lt->tm_year+1900, lt->tm_mon+1,     lt->tm_mday);
        lt->tm_hour+=24; // adding 24 hours
        t = mktime(lt);
    }
    return 0;
}

By the way it works dates behind epoch. At least on my gcc version 4.4.3 in x86_64 GNU/Linux

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 754640

You probably want the year loop before the month loop before the day loop (the reverse of the current order).

You are going to need to make the testing for maximum day of the month cleverer (you need to know the rules for leap years (noting that 1900 was not a leap year, pace MS Excel, and 2000 was).

You can use %02d or %.2d to print 2 digits for the month and day, so you only need a single printf() statement.

Upvotes: 0

Nitin Midha
Nitin Midha

Reputation: 2268

You can actually have 4 combinations of day and month in which you may or may not prefix with 0, which you are trying to handle with single if else.

Case 1: Both day and month <10, handled by first if.

Case 2: Day > 10 and Month < 10, un-handled

Case 3: Day < 10 and Month > 10, un-handled

Case 4: Both are > 10. Handled in else.

%02d is the option to handle all the cases.

Upvotes: 1

Related Questions