Reputation: 855
I've got an issue which I can't find a solution. Or at least a "good" one. I want to find the last day of the month given a month and a year in C.
For example :
last_day(10, 2017) > 31
last_day(02, 2017) > 28
last_day(02, 2016) > 29
last_day(01, 2017) > 31
last_day(12, 2010) > 31
last_day(X, Y) > X is the month, Y the year
Here is my idea: Get the day on the month X + 1, of year Y. Remove 1 day from this date.
I would like to know if there is a better solution than that, since that will a make "lot" of operation for a "simple" thing.
Thanks.
Edit : https://ideone.com/sIISO1
#include <stdio.h>
#include <time.h>
#include <string.h>
int main(void) {
struct tm tm;
char out[256];
memset(&tm, 0, sizeof(struct tm));
tm.tm_mon = 1;
tm.tm_mday = 0;
strftime(out, 256, "%d-%m-%Y", &tm);
printf("%s", out);
return 0;
}
I've tested by using struct tm, and day = 0, in order to get the previous day but did not work
Upvotes: 0
Views: 1728
Reputation: 855
Ask point out in the commentary, I've complexify the problem way to much.
I have been inspired by what @Agnishom Chattopadhyay said in comment, which is get the date from a lookup table.
But I did make a function which did that
#include <stdio.h>
int days_in_month(int month, int year) {
if ( year < 1582 ) return 0; /* Before this year the Gregorian Calendar was not define */
if ( month > 12 || month < 1 ) return 0;
if (month == 4 || month == 6 || month == 9 || month == 11) return 30;
else if (month == 2) return (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? 29 : 28);
return 31;
}
int main() {
printf("%d\n", days_in_month(10, 2017));
printf("%d\n", days_in_month(2, 2000));
printf("%d\n", days_in_month(2, 1300)); // Does not work !
printf("%d\n", days_in_month(2, 2018));
printf("%d\n", days_in_month(2, 2016));
}
Upvotes: 1