Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C get day of year from date

Tags:

c

date

I want to convert a date like 01/31/2013 to the day of year (31 in this case). This date is from user input, so I also need to check if it is a valid date. I know I can calculate day of year by myself like below:

int get_yday(int mon, int day, int year)
{
    int yday=0;
    mon--;

    switch (mon){
    case 12:
        yday+=31;
    case 11:
        yday+=30;
    ....
    case 2:
        if (is_leap_year(year)) yday+=29;
        else yday+=28;
    .....

However, this means I need to check user input by myself like

switch(month){
case 1:
    if (day > 31 || day < 0) {...}
case 2:
    if (...check leap year and day ...) {...}

Is there a built-in API in C to get the day of year easily?

I have a solution below, but I want to know if there is a better one:

1. creating a tm struct of 01/31/2013 00:00:00
2. get timestamp by mktime()
3. convert timestamp to struct tm by localtime()
4. get tm_yday from tm struct
like image 330
Yalieee Avatar asked Oct 15 '13 09:10

Yalieee


1 Answers

Is easy using offsets:

#include <stdio.h>

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

int get_yday(int mon, int day, int year)
{
    static const int days[2][13] = {
        {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
        {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
    };
    int leap = yisleap(year);

    return days[leap][mon] + day;
}

int main(void)
{
    int day = get_yday(1, 31, 2013);

    printf("%d\n", day);
    return 0;
}
like image 65
David Ranieri Avatar answered Sep 29 '22 23:09

David Ranieri