How to get the number of the day from the beginning of the year to a given date in C

2 Answers

0 votes
#include <stdio.h>
#include <stdbool.h>
 
bool IsLeapYear(unsigned int year) {
    return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
 
int GetDayOfYear(unsigned int year, int month, int day) {
    unsigned short days[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
 
    if (IsLeapYear(year) && month > 2)
        return days[month - 1] + day + 1;
 
    return days[month - 1] + day;
}
 
int main() {
 
    int dayOfYear = GetDayOfYear(2023, 5, 15);
 
    printf("%d", dayOfYear);
}
 
 
 
 
/*
run:
 
135
 
*/

 



answered May 15, 2023 by avibootz
edited Dec 13, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdbool.h>

bool isLeapYear(int year) {
    return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
}

// Function to get the day number in the year
int dayOfYear(int day, int month, int year) {
    // Days in each month
    int daysInMonth[] = {31, 28, 31, 30, 31, 30,
                         31, 31, 30, 31, 30, 31};

    // Adjust February for leap year
    if (isLeapYear(year)) {
        daysInMonth[1] = 29;
    }

    int dayNum = 0;

    // Sum days of previous months
    for (int i = 0; i < month - 1; i++) {
        dayNum += daysInMonth[i];
    }

    // Add current day
    dayNum += day;

    return dayNum;
}

int main() {
    int day = 15, month = 5, year = 2023;

    printf("Day number in year: %d\n", dayOfYear(day, month, year));

    return 0;
}



/*
run:
 
Day number in year: 135
 
*/

 



answered Dec 13, 2025 by avibootz
...